sql联合查询的相关问题

数据库 mysql

表a
id name

1 one
2 two
表b
id aid headimg createtime
1 1 http://qiuniu1 2017-12-13
2 1 http://qiuniu2 2017-12-14
3 2 http://qiuniu3 2017-12-15
4 2 http://qiuniu4 2017-12-16
查询条件:表a的id 对应表b的aid
b中的数据按时间取最新的一条
查询结果:
name headimg

one http://qiuniu2
two http://qiuniu4

select aa.name name,bb.headimg headimg from a aa inner join b bb on aa.id=bb.aid where aa.id='1'

select top 1 aa.name name,bb.headimg headimg from a aa, b bb where aa.id=bb.aid order by bb.createtime desc(如果a的idb里面没有的话会直接跳过)

我想你要的语句应该是这样的:

 SELECT  a.name,b.headimg FROM a
LEFT JOIN b ON a.id = b.aid AND NOT EXISTS(SELECT 1 FROM b as tb2 WHERE tb2.aid=b.aid AND createtime>b.createtime)

select * from a inner join b on a.a.id = b.aid and not exists(select 1 from b as t where t.aid=b.aid and t.createtime>b.createtime)

select a.name b. headimg from a
join b
on a.id = b.aid
and not exists(select 1 from b as tb2 where tb2.aid=b.aid and createtime>b.createtime)

SELECT c.name,c.headimg,FROM (
SELECT a.name,b.headimg,b.cbokereatetime FROM a,b
WHERE a.id=b.aid ORDER BY b.createtime DESC) c GROUP BY c.name;