简体   繁体   English

SQL-联接表并非总是如此

[英]SQL - Joining tables BUT not always

I need to perform a query SELECT that joins three tables (no problem with that). 我需要执行连接三个表的查询SELECT(这没有问题)。 Nonetheless, the third table can, or NOT, have any element that match the joining KEY. 但是,第三个表可以具有或不具有与联接KEY匹配的任何元素。

I want ALL data from the first two tables and if the ITEMS have ALSO information in the third table, fetch this data to. 我想要前两个表中的所有数据,如果ITEMS在第三个表中也有ALSO信息,则将此数据提取到其中。

For example, imagine that the first table have a person, the second table have his/her address (everyone lives anywhere), the third table stores the driving license (not everyone has this) - but I need to fetch all data whether or not people (all people) have driving license. 例如,假设第一个表有一个人,第二个表有他/她的地址(每个人都住在任何地方),第三个表存储了驾驶执照(并非每个人都有这个)-但是我需要获取所有数据,无论是否人(所有人)都有驾驶执照。

Thanks a lot for reading, if possible to give you suggestion / solution! 非常感谢您的阅读,如果可以给您建议/解决方案!

Use LEFT JOIN to join the third table. 使用LEFT JOIN第三个表。 Using INNER JOIN a row has to exists. 使用INNER JOIN必须存在一行。 Using LEFT JOIN , the 'gaps' will be filled with NULL s. 使用LEFT JOIN ,“空白”将填充为NULL

SELECT
  p.PersonID, -- NOT NULL
  -- dl.PersonID, -- Can be null. Don't use this one.
  p.FirstName,
  p.LastName,
  a.City,
  a.Street,
  dl.ValidUntilDate
FROM
  Person p
  INNER JOIN Addresse a ON a.AddressID = p.HomeAddressID
  LEFT JOIN DrivingLicence dl ON dl.PersonId = p.PersonID

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

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