我有2个表和结果,如下图所示:MySQL DB
加入这两个表的最佳方法是什么,所以我们得到如上所示的结果。
SELECT * FROM (SELECT id, desc FROM table2) as T1
LEFT JOIN (SELECT * FROM table1) as T2 ON T1.id = T2.id
我猜我的SQL无效。
答案 0 :(得分:1)
使用带有coalesce
的左连接来优先处理表2的值(如果存在),但如果不存在则返回表1的值。
select t1.id,
coalesce(t2.desc, t1.desc) as desc,
t1.d1, t1.d2
from table1 t1
left join table2 t2
on t2.id = t1.id
order by t1.id
答案 1 :(得分:1)
您可以LEFT JOIN
使用COALESCE
:
SELECT t1.id, COALESCE(t2.desc, t1.desc) AS desc, t1.D1, t1.D2
FROM table1 as T1
LEFT JOIN table2 as T2 ON T1.id = T2.id
答案 2 :(得分:0)
您可以使用ifnull:
SELECT t1.id, ifnull(t2.desc, t1.desc) AS desc, t1.D1, t1.D2
FROM table1 as T1
LEFT JOIN table2 as T2 ON T1.id = T2.id
coalesce
或case .. when
也是可能的。全部与left join