sql 无需排队即可加入

sql join without some lines

我想加入 tableA相同的 tableA 使用 group_id=group_id在table_type上的类型条件不同
table一个

    id  name    type_id group_id
--------------------------------
    1   name1   4   2   
    2   name2   3   1
    3   name3   3   2
    4   name4   3   3
    5   name5   4   3

输入table:

id  code
------------
3   out
4   in


我想得到 return 作为 :

    id  name    type_id group_id    bro_id  bro_name
---------------------------------------------------------
    2   name2   3   1       1   name1
    3   name3   3   2   
    4   name4   3   3       5   name5

我尝试了 sql:

SELECT tA.id,tA.name,tt.code,tAi.id AS "bro_id",tAi.name AS "bro_name",tti.code
FROM tablea tA 
INNER JOIN table_type tt ON (tA.type_id=tt.id and tt.code='OUT')
LEFT JOIN tablea tAi ON (tA.group_id=tAi.group_id and tA.id!=tAi.id ) 
INNER JOIN table_type tti  ON (tti.id=tAi.type_id and tti.code='IN')

但我听不到这条线:

3   name3   3   2   null    null

您已使用内部联接查找兄弟的类型。 应该也是左连接:

LEFT join table_type tti  on (tti.id=tAi.type_id and tti.code='in')

SQLDFIDDLE

您需要将左连接的 ON 语句移动到查询的底部:

SELECT tA.id,tA.name,spt.code,tAi.id AS "bro_id",tAi.name AS "bro_name",tti.code,tA.date
FROM tableA tA 
INNER join table_type tt on (tA.type_id=tt.id and tt.code='out')
LEFT join tableA tAi -- <---on statement removed
INNER join table_type tti  on (tti.id=tAi.type_id and tti.code='in')
    on (sp.group_id=spi.group_id and sp.id!=spi.id ) -- <--- moved to here

您最后的 INNER JOIN 基本上将查询限制为仅存在 tAi 的项目。这是因为您将 tti 直接连接到 tA 和 tt,而您希望 LEFT JOIN 连接两个表中每个子查询。

您可以执行 LEFT JOINing 最后两个表的另一个建议答案,但这并不是很理想,而且偶尔会出错(不过我认为在这种情况下会很好)。