从两个不同的表中获取数据

时间:2016-02-17 08:59:39

标签: mysql

table name->city                         table name->history

id       city                              id          history
----------------                           -----------------------  
1       mumbai                             1      Lorem ipsum Amet
2       delhi                              2      Lorem ipsum Amet
3       chennai
4       patna
5       ranchi
6       noida

预期产出: -

     city              hisoty             history_id  
------------------------------------------------------                        
mumbai            Lorem Ipsum Amet          1  
delhi             Lorem Ipsum Amet          2     
chennai
patna
ranchi
noida

请帮我查询以获得预期的输出

2 个答案:

答案 0 :(得分:2)

执行LEFT OUTER JOIN之类的

select c.city,
coalesce(h.history,''), 
coalesce(h.id,'') as history_id
from city c
left join history h on c.id = h.id;   

答案 1 :(得分:1)

使用SQL left join获取更多LEFT JOIN

select c.city,
h.history, h.id as history_id
from city c
left join history h on c.id = h.id;