简体   繁体   中英

SQL - Joining tables BUT not always

I need to perform a query SELECT that joins three tables (no problem with that). Nonetheless, the third table can, or NOT, have any element that match the joining 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.

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. Using INNER JOIN a row has to exists. Using LEFT JOIN , the 'gaps' will be filled with NULL s.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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