【问题标题】:How to conditionally apply a 'where' condition only when there is an entry exists仅当存在条目时如何有条件地应用“where”条件
【发布时间】:2013-01-07 00:46:09
【问题描述】:

我想基于其他 3 个表创建一个临时表。但是有一个条件可能适用也可能不适用,具体取决于第三张表中是否存在条目。如何在“where”条件下插入不同的案例?

select table1.tran_num, table2.impact
from table 1, table2, table3
where tables1.tran_num = 12345
and table1.index = table2.index
"and case when table2.index in table3.index then table2.version = table3.version"

【问题讨论】:

  • 尝试为您的第三个表创建另一个 Select ,并使用运算符创建或不创建它。而且,由于您正在构建基于其他 3 个表的第 3 个表,视图不是替代方案吗?

标签: sql select join


【解决方案1】:

你只需要使用INNER JOIN

select  table1.tran_num, table2.impact
from    table1 
        INNER JOIN table2
            ON table1.index = table2.index
        INNER JOIN table3
            ON table2.version = table3.version
where   tables1.tran_num = 12345

如果所有记录都存在于所有表中,上述查询将仅显示记录。但是,如果您希望在 table2 的列 version 不存在于 table3 上时仍显示记录,则需要 LEFT JOIN

select  table1.tran_num, table2.impact
from    table1 
        INNER JOIN table2
            ON table1.index = table2.index
        LEFT JOIN table3
            ON table2.version = table3.version
where   tables1.tran_num = 12345

要了解有关加入的更多信息,请参阅下面的文章

【讨论】:

  • 如果我看到你的答案或者至少知道你在附近,我不会发布 ;-) 我的概念完全基于 exists,因为我没有看到来自 OP 的任何查询。更不用说认为他正在尝试基于存在插入数据。事情很简单。
【解决方案2】:

使用类似于

的左连接和where子句
where joined_table.id is null or joined_table.filter_col in (1,2,3)

例如:

select t1.id, t2.id
from table1 t1
left join table2 t2
 on t1.fk_id = t2.id
where t2.id is null or t2.filter_col in (1,2,3,4)

上面的查询将获取所有来自 t1 的不在 t2 上的记录,或者来自 t1 的记录在 t2 上并且它们在 t2 上的等效 filter_col 在 (1,2,3,4) 中

【讨论】:

    【解决方案3】:

    你可以试试下面的逻辑:

     IF EXISTS ( SELECT *
     FROM tablea a Left JOIN tableb b 
    ON a._id = b._id 
    Left JOIN tablec c ON b._id = c._id 
     SELECT 1 ELSE SELECT 0
    

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多