我有两个表,我从两个表中获取值,情况是第一个表始终包含记录,但第二个表可能包含也可能不包含记录。
这里是表格
TAB1<br/>
id | rank
1 | TL
2 | PL
3 | MG<br/>
TAB2<br/>
num | id | swiped_on
1 | 1 | 20-4-14
2 | 1 | 21-4-14
3 | 3 | 25-4-14
我想要的结果是,(只有第二个表中的一条记录)
id | rank | swiped_on
1 | TL | 21-4-14
2 | PL | -------
3 | MG | 25-4-14
请帮忙
最佳答案
您可以将左连接与表 tab2 中的子选择结合使用
select t.*,t1.swiped_on
from TAB1 t
left join (select id , max(swiped_on) swiped_on
from TAB2 group by id
) t1
on(t.id = t1.id)
Fiddle demo
或者只是从 tab2 获取 swiped_on 的最大值
select t.*,max(t1.swiped_on) swiped_on
from TAB1 t
left join TAB2 t1
on(t.id = t1.id)
group by t.id
Fiddle demo
关于mysql - 连接两个表,从两个表中选择值,第二个表没有记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25357629/