我有以下SQL查询:
SELECT
C.Child_ID,
C.Child_Name AS Name,
C.Child_Surname AS Surname,
C.Birthday AS DOB,
C.Location,
C.Primary_Image,
U.Text AS MostRecentUpdate,
U.Update_Date,
S.End_Date
FROM Children as C, Sponsors as S, Updates as U
WHERE
S.User_ID=@UserID
AND C.Child_ID=S.Child_ID
AND C.Child_ID=U.Child_ID
AND U.Update_Date = (SELECT
MAX(Update_Date)
FROM Updates as U2
WHERE U2.Child_ID=S.Child_ID)
AND S.End_Date>GETDATE()
ORDER BY C.Child_Name ASC
选择儿童的详细信息,以及儿童的最新更新(适用于赞助网站)。问题是,如果孩子还没有任何更新(更新类似于Facebook状态),则不会返回任何详细信息。
如果没有更新,是否有办法修改此查询以仅返回子详细信息?
答案 0 :(得分:4)
使用left outer join
:
SELECT C.Child_ID, C.Child_Name AS Name, C.Child_Surname AS Surname,
C.Birthday AS DOB, C.Location, C.Primary_Image,
U.Text AS MostRecentUpdate, U.Update_Date, S.End_Date
FROM Children as C
inner join Sponsors S
on C.Child_ID=S.Child_ID
left outer join Updates U
on C.Child_ID=U.Child_ID
AND U.Update_Date=(SELECT MAX(Update_Date) FROM Updates as U2 WHERE U2.Child_ID=S.Child_ID)
WHERE S.User_ID=@UserID AND S.End_Date>GETDATE()
ORDER BY C.Child_Name ASC
答案 1 :(得分:1)
没有更新时没有结果,因为您正在从子表到更新表进行内部联接。
我建议您将其更改为较新的ansi兼容连接语法,而不是旧的连接语法。然后,您只需将更新的连接更改为左外连接。
应该这样做。
祝你好运。