简体   繁体   English

如果一个字段为空,SQL查询将不返回任何内容

[英]SQL Query returns nothing if one field is empty

I have the following SQL query: 我有以下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

Which selects a Child's details, and the child's latest update (it's for a sponsorship website). 选择孩子的详细信息和孩子的最新更新(用于赞助网站)。 The problem is that if the child does not have any updates yet (updates are similar to a facebook status), no details are returned. 问题是,如果孩子还没有任何更新(更新类似于Facebook状态),则不会返回任何详细信息。

Is there a way of modifying this query to return just the child details, if no updates are present? 如果不存在更新,是否可以修改此查询以仅返回子项详细信息?

Use a left outer join : 使用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

You get no results when there are no updates because you are doing an inner join from the child table to the updates table. 当没有更新时,您将不会获得任何结果,因为您正在执行从子表到更新表的内部联接。

I suggest you change it over to the newer ansi compatible join syntax rather than the older join syntax. 我建议您将其更改为较新的ansi兼容连接语法,而不是较旧的连接语法。 Then you can just change the join with updates to be a left outer join. 然后,您可以将带有更新的联接更改为左外部联接。

That should do it. 那应该做。

good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM