【问题标题】:case statement in sql with multiple joins具有多个连接的sql中的case语句
【发布时间】:2015-09-24 06:29:35
【问题描述】:

我有 2 个表连接在一起并返回我想要的:

SELECT a, b, table_one.c, d, e 
from table_one INNER JOIN table_two ON table_two.c=table_one.d 
WHERE table_two.c

我有第三个表 table_three,它也有 c 列。我需要一个带有标志(如布尔值)的列,该值是否出现在第三个表中。 我一直在尝试为此做一个 case 语句和一个左连接,但我无法弄清楚语法。

我知道我可以将案例作为 SELECT 之后的另一列,例如:

SELECT a, b, table_one.c, d, e
     , case table_three.c 
           when table_three.other_column_in_table_three ISNULL THEN true           
           ELSE false 
       END 
from table_one INNER JOIN....

但我不确定这是否完全正确,而且我不知道如何在此查询中添加左连接。这是正确的想法吗?如果是,语法是如何工作的?

【问题讨论】:

  • 您使用的是什么 DBMS?
  • 案例表达,不是案例陈述...

标签: sql postgresql join


【解决方案1】:

更简单的方法

select a, b, table_one.c, d, e
     , table_three.other_column is not null as flag
from table_one inner join table_two on table_one.d = table_two.c
     left join table_three on -- put here the relation rules between table_three
                              -- and the other tables

【讨论】:

  • 所以对于表 3 之间的关系规则,我认为应该只是: table_three.c=table_one.d ---就像加入 table_one 和 table_two 但我需要什么“和其他表“?
【解决方案2】:

在 MSSQL 中你可以试试:

SELECT a, b, table_one.c, d, e, ISNULL(table_three.c, true)
from table_one
INNER JOIN table_two ON table_two.c = table_one.d
LEFT JOIN table_three ON table_two.c = table_three.c

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2016-07-31
    • 2012-03-02
    • 1970-01-01
    相关资源
    最近更新 更多