SQL查询的问题

时间:2016-09-20 13:13:13

标签: mysql sql database

我有2个表和结果,如下图所示:MySQL DB

enter image description here

加入这两个表的最佳方法是什么,所以我们得到如上所示的结果。

SELECT * FROM (SELECT id, desc FROM table2) as T1 
LEFT JOIN (SELECT * FROM table1) as T2 ON T1.id = T2.id

我猜我的SQL无效。

3 个答案:

答案 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

coalescecase .. when也是可能的。全部与left join

一起