关于联表取唯一值的SQL
A、B表关系 是 1 VS n,对应字段分别是 ID、AID
A.ID 的值 在 B.AID 不一定都有,但是 B.AID 的值 一定在A.ID中存在
想达到下面SQL的效果,怎么写更好:
Select A.*,(select Top 1 B.b1 From B Where B.AID = A.ID Order By B.DateT),
(select Top 1 B.b2 From B Where B.AID = A.ID Order By B.DateT),…… From A Where A.State = 1
怎么写都不对~~,哪位大大指点迷经
------解决方案--------------------Select A.*,t.b1,t.b2
From A left join b t on a.id=t.bid
Where A.State = 1
and not exists(select 1 from b where aid=t.aid and DateT <t.DateT)
------解决方案--------------------LZ好像要的是实现*表吧~
------解决方案--------------------Select
A.*,
D.ID AS BID,
D.DateT
From A Left Join
(Select B.* From B C Where DateT In (Select Max(DateT) From B Where AID = C.AID)) D
On A.ID = B.AID