我的查询和它的'可以只有两个表:
SELECT
CASE WHEN p.name IS NULL THEN i.number2 ELSE p.name END as Names
FROM tbl1 p
RIGHT JOIN tbl2 i ON p.number = i.number2
GROUP BY i.number2
我有四张桌子:
tbl1
number name
+72001 Patrick
+72002 Ivan
tbl2
number2 text2
+72001 ABC1
+72003 ABC2
tbl3
number3 text3
+72002 ABC5
+72004 ABC6
tbl4
number4 text4
+72001 ABC5
+72005 ABC6
如果我想要使用4个表并且结果如下:
number
Patrick
Ivan
+72003
+72004
+72005
我尝试之后,现在正在运行:
SELECT
CASE WHEN p.name IS NULL THEN i.number2 ELSE p.name END AS NAMES
FROM tbl1 p
RIGHT JOIN tbl2 i ON p.number = i.number2
GROUP BY NAMES
UNION
SELECT CASE WHEN p.name IS NULL THEN m.number3 ELSE p.name END AS NAMES
FROM tbl1 p
RIGHT JOIN tbl3 m ON p.number = m.number3
GROUP BY NAMES
UNION
SELECT CASE WHEN p.name IS NULL THEN n.number4 ELSE p.name END AS NAMES
FROM tbl1 p
RIGHT JOIN tbl4 n ON p.number = n.number4
GROUP BY NAMES