日期:2014-05-18  浏览次数:20506 次

一个苦思不解的SQL查询,请高手解答下
有A表和B表
A表有AID ANAME
B表有ID BID DATETIME
AID是A表主键
ID是B表的 主键
AID和BID存在关联

我想实现将B表按最近时间的一条记录匹配A表中的记录,A表中所有记录都会被查出,我之前用 下面语句只能查出A和B都有对应的记录
SQL code
SELECT * FROM A,B WHERE B.DATETIME=(SELECT MAX(DATETIME) WHERE A.AID=B.BID) AND A.AID=B.BID



谢谢

------解决方案--------------------
SQL code
SELECT * FROM A left join 
(select * from B t where not exists(select 1 from B where BID=t.BID and [DATETIME
]>t.DATETIME
)) n
 on A.AID=n.BID

------解决方案--------------------
SQL code
select m.* , n.*
from a m left join b n
on m.AID = n.BID and n.DATETIME = (select max(DATETIME) from b where bid = n.bid)

select m.* , n.*
from a m left join b n
on m.AID = n.BID and not exists (select 1 from b where bid = n.bid and DATETIME > n.DATETIME)

------解决方案--------------------
select * 
from a
left join b
on a.AID = b.BID
and b.DATETIME=(SELECT distinct MAX(DATETIME) WHERE a.AID=b.BID)