我有两个表要加入,我想从联接表中知道是否有一个与连接条件匹配的退出行。我不想返回连接表的所有行。
示例:
Table A
ID Name
1 Bob
2 Sally
3 Joe
Table B
Num ID Data
1 1 anything
2 1 some more
3 3 thats it
我希望它返回表A中的所有行,但我只想知道表B上是否有匹配的ID。我不想返回所有匹配的行。
所以我的输出看起来像这样:
ID Name Has Data
1 Bob Yes
2 Sally No
3 Joe Yes
我不希望输出看起来像这样(它目前做的):
ID Name Has Data
1 Bob Yes
1 Bob Yes
2 Sally No
3 Joe Yes
这是我的问题:
SELECT a.ID, Name
FROM table_a AS a
LEFT JOIN (SELECT DISTINCT b.ID FROM table_b) AS b ON b.ID = a.ID
我收到此错误消息: “字段列表”中的未知列“b.ID”
答案 0 :(得分:1)
SELECT a.ID, Name
CASE WHEN b.ID IS NULL THEN 'No' ELSE 'Yes' END as [Has data]
FROM table_a AS a
LEFT JOIN table_b ON b.ID = a.ID
GROUP BY a.Id, Name
SELECT a.ID, Name
CASE WHEN EXISTS (SELECT 1
FROM table_b b
WHERE b.ID = a.Id) THEN 'Yes'
ELSE 'No' END as [Has data]
FROM table_a AS a
如果LEFT JOIN没有返回行,则b.ID将为null,然后使用CASE语句返回yes或no,具体取决于它的值。