【问题标题】:sql join without some lines没有一些行的sql连接
【发布时间】:2015-09-08 11:40:06
【问题描述】:

如果 table_type 上的类型不同,我想使用 group_id=group_id 将 tableA 与 same tableA 连接起来
表A

    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

输入表格:

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


我想得到回报:

    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

【问题讨论】:

  • 你想要的结果中 bro_id 字段背后的逻辑是什么?
  • bro_id是group_id相同的线的兄弟
  • @DanBracuk bro_id 背后的逻辑来判断 type = IN 是否存在
  • 区分in、out 代码有什么意义,因为这不会反映在输出中?
  • 仅供参考,您在所需的输出中有错误,name2 没有兄弟。 name3 有一个兄弟:name1。

标签: sql postgresql join left-join


【解决方案1】:

您需要将左连接的 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 这两个最后两个表的另一个建议的答案,但这并不是很理想,并且偶尔会出错(不过我认为在这种情况下会很好)。

【讨论】:

  • 这是一个有效的,我认为比我更好的回应。 http://sqlfiddle.com/#!15/00f54/6 点赞!
  • 关于这种移动 ON 语句案例的任何文档?
  • 有趣点@m3asmi。我已经看了看,实际上很难在上面找到任何东西。正如我所提到的,我认为左连接是连接子查询,而不仅仅是连接一个表。
【解决方案2】:

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

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

SQLDFIDDLE

【讨论】:

  • 无法获取线路:s
  • 这不可能。查询 select * FROM tableA tA INNER join table_type tt on (tA.type_id=tt.id and tt.code='out') 给你 3 行?
  • 如果你只在上面的查询中添加左连接,你不会丢失任何行:)
猜你喜欢
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多