2016-09-20 53 views
1

我有2個表和結果如下所示的圖像:MySQL數據庫與SQL發出查詢

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不工作。

+0

表2爲T1,和表1爲T2 ......可怕。 – jarlh

回答

1

您可以使用LEFT JOINCOALESCE

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 
1

使用左與​​3210參加如果它們存在表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 
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 

​​3210或case .. when也是可能的。所有連同left join