【问题标题】:SQL with dynamic exclusion, condensed into one query (SQLite)具有动态排除的 SQL,浓缩为一个查询 (SQLite)
【发布时间】:2011-08-21 21:38:08
【问题描述】:

我有两张桌子: 表 1:id1、field1、field2、field3 表2:id2、field1、field3

我需要的是:

"select id2 from table2 where field1 = x and field3 = y;"

如果返回空,则执行并处理来自:

"select field2 from table1 where field1 = x and field3 = y;"

有没有办法在 SQLite 中的单个查询中执行此操作?

【问题讨论】:

    标签: sqlite select


    【解决方案1】:

    假设表在field1field3 上是可连接的,那么这样的事情应该可以工作(警告:未经测试):

    select
      case when sum(count_id2)>0 then a.id2
      else b.field2 end as column
    from(
      select id2,count(1) as count_id2
      from table2
      where field1=x and field3=y
      group by id2
    )a
    join(
      select id2,field2
      from table1
      join table2
      using(field1,field3)
      where field1=x and field3=y
    )b
    using(id2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      • 2016-07-27
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多