我有2张桌子要加入。
Table 1
是一个主表,包含一组唯一的行。
ID DESCRIPTION
01 Alpha
02 Gamma
03 Delta
04 Beta
Table 2
是一个详细信息表,其中包含许多行,只有一些行与主表匹配。
ID INFO MASTER_ID
0001 abc 02
0002 def 02
0004 xyz 01
0005 mno 04
我想加入表格以产生以下结果:
Alpha "has detail"
Gamma "has detail"
Delta "does not have detail"
Beta "has detail"
而不是:
Alpha "has detail"
Gamma "has detail"
Gamma "has detail"
Delta "does not have detail"
Beta "has detail"
后面的输出返回Gamma两次,我只希望它返回一次。
我尝试了LEFT JOIN,RIGHT JOIN,INNER JOIN,但没有一个能产生我想要的结果。
感谢您的帮助。
答案 0 :(得分:3)
使用LEFT JOIN
可能你错过了什么
SELECT CONCAT(a. description, IF(b.master_ID IS NOT NULL, ' has detail',' does not have detail'))
FROM table1 a
LEFT JOIN (SELECT DISTINCT master_ID FROM table2) b
ON a.ID = b.master_ID
答案 1 :(得分:1)
也许是这样的:
SELECT
Table1.DESCRIPTION,
(
CASE
WHEN EXISTS(SELECT NULL FROM Table2 WHERE Table2.MASTER_ID=Table1.ID)
THEN 'has detail'
ELSE 'does not have detail'
END
) AS has
FROM
Table1
答案 2 :(得分:1)
只是一种不同的方法:
SELECT
table1.description,
IF((EXISTS(SELECT master_id from table2 where table2.master_id = table1.id)),
'has detail',
'does not have detail') As Status
FROM table1
答案 3 :(得分:0)
SELECT a.Description, IF(b.Info, "has detail", "does not have detail") as Status
FROM Table_1 a
LEFT OUTER JOIN Table_2 b
ON a.MASTER_ID = b.MASTER_ID
GROUP BY 1,2;
答案 4 :(得分:0)
如果你的输出包含细节部分,那么你必须要么看到两行(因为它是有效的结果),要么你需要通过选择FIRST,MAX等来聚合结果。
如果你自己不需要细节值,那么替代方法是做两个SELECT并使用UNION:
SELECT DISTINCT Table1.Description, "does not have detail" as Comment
FROM Table1
LEFT JOIN Table2 ON (Table1.ID = MASTER_ID)
WHERE Table2.id IS NULL
UNION
SELECT DISTINCT Table1.Description, "has detail" as Comment
FROM Table1
LEFT JOIN Table2 ON (Table1.ID = MASTER_ID)
WHERE Table2.id IS NOT NULL
答案 5 :(得分:0)
您也可以使用groupby
来实现此目的SELECT a.Description, IF(count(b.id) > 0, "has detail", "does not have detail") as Status
FROM Table1 a
LEFT OUTER JOIN Table2 b
ON a.iD = b.MASTER_ID
GROUP BY a.Description ORDER BY a.Description ASC