我希望以下列方式加入3个表:
SELECT a.id
FROM tableA AS a
LEFT JOIN tableB AS b ON a.id = b.id
LEFT JOIN tableC AS c ON a.id = c.id
WHERE
b.name = c.name OR b.name IS NULL OR c.name IS NULL;
我无法确定,表b或c将有一行要加入,但如果两者都有一行要加入,则name列必须相同。
我的问题是:我想选择此名称列,但我只想选择一次。所以,如果b和c有一行要连接,我想要其中任何一个的名称,如果只有一个有一行要加入,我想要该行的名称。 结果中的列名在每种情况下都应该相同。
表格示例
表A
id
----
1
2
3
4
tableB的
id | name
----|------
2 | X
3 | Y
表C
id | name
----|------
2 | Q
3 | Y
4 | Z
期望的结果:
id | name
----|------
1 | (NULL)
2 | X (name is from tableB)
2 | Q (name is from tableC)
3 | Y (name is from tableB or tableC)
4 | Z (name is from tableC)
答案 0 :(得分:0)
SELECT a.id, IFNULL(b.name, c.name)
FROM tableA AS a
LEFT JOIN tableB AS b ON a.id = b.id
LEFT JOIN tableC AS c ON a.id = c.id
WHERE
b.name = c.name OR b.name IS NULL OR c.name IS NULL;
此查询应返回您想要的内容。 IFNULL(X, Y)
通过说如果X为null,则使用Y.在您的示例中,如果b.name不为null,则将显示b.name。如果b.name为null,则将显示c.name。如果某些内容在c.name中,则会打印该名称,但如果c.name为null NULL
将按您的要求显示。
答案 1 :(得分:0)
我希望这会对你有所帮助
SELECT
a.id,
(CASE COALESCE(b.`name`, '') WHEN '' THEN c.`name` ELSE b.`name` END) AS name2,
b.`name` AS B,
c.`name` AS C
FROM foo1 AS a
LEFT JOIN foo2 AS b ON (a.id = b.id)
LEFT JOIN foo3 AS c ON (a.id = c.id)
ORDER BY a.id;
答案 2 :(得分:0)
另一种可能性,如果没有必要,最好完全摆脱LEFT。
SELECT a.id, b.name
FROM tableA AS a
LEFT JOIN tableB AS b ON a.id = b.id
UNION
SELECT a.id, c.name
FROM tableA AS a
LEFT JOIN tableC AS c ON a.id = c.id
如果您不想要name为NULL的行,请删除LEFT