SELECT BabyInformation.* , t1.*
FROM BabyInformation
LEFT JOIN
(SELECT * FROM BabyData
GROUP BY BabyID
ORDER By Date DESC ) AS t1 ON BabyInformation.BabyID=t1.BabyID
这是我的查询。我希望根据日期获得最新的BabyData
元组。
BabyInformation
应该与babyData
联系,但每个宝宝只有一行......
我试过TOP(1)
,但这只适用于第一个孩子
答案 0 :(得分:3)
这是一种方法,还有其他方法可以更快,但我相信这对初学者来说是最清楚的。
SELECT BabyInformation.*, BabyData.*
FROM BabyInformation
JOIN
(SELECT BabyID, Max(Date) as maxDate FROM BabyData
GROUP BY BabyID
) AS t1
ON BabyInformation.BabyID=t1.BabyID
Join BabyData ON BabyData.BabyID = t1.BabyID and BabyData.Date = t1.maxDate
答案 1 :(得分:1)
这应该这样做:
SELECT bi.* , bd.*
FROM BabyInformation [bi]
LEFT JOIN BabyData [bd]
on bd.BabyDataId = (select top 1 sub.BabyDataId from BabyData [sub] where sub.BabyId = bi.BabyId order by sub.Date desc)
我假设BabyData表中有一个名为'BabyDataId'的列。