查询返回相关结果,但如果没有相关行仍然是一行

时间:2017-12-10 04:27:09

标签: sql-server tsql

考虑人拥有汽车拥有车轮的关系。

表: 人   是PersonID   PERSONNAME

汽车   CarID   PersonID(fkey to person)   CarName

轮式   WheelID   CarID(车钥匙)   位置

我需要一个查询,向我展示属于一个人的所有轮子,如果没有轮子,我仍然需要一个带有人名的行。

Sally 
  Car 1
    Wheel 1
    Wheel 2
  Car 2
    Wheel 3
  Car 3
   <no related wheels>

Bob
   <no related cars>

查询应该返回列PersonName,CarName,Wheel.Position

我希望结果为:

Sally, Car 1, Wheel 1
Sally, Car 1, Wheel 2
Sally, Car 2, Wheel 3
Bob, null, null

我需要它是一个T-SQL查询,并且不喜欢动态SQL。

我试过

select p.PersonName, c.CarName, w.Position
from Person p
left join Car c on c.PersonID = p.PersonID
left join Wheel w on w.CarID = c.CarID

但这不起作用,因为我得到了额外的结果: Saly, Car3, null。使用left outer会产生同样的问题。

2 个答案:

答案 0 :(得分:0)

SELECT p.name, c.id, w.id
  FROM person p, car c, wheel w
 WHERE p.id = c.id_person
   AND c.id *= w.id_car

         SELECT p.name, c.id, w.id
           FROM person p, car c
LEFT OUTER JOIN wheel w ON c.id = w.id_car
          WHERE p.id = c.id_person

根据添加到问题的其他信息,查询将是:

         SELECT p.id, cw.id_car, cw.id_wheel
           FROM person p
LEFT OUTER JOIN (SELECT c.id as id_car, c.id_person, w.id as id_wheel
                   FROM car c, wheel w
                  WHERE c.id = w.id_car) cw
             ON p.id = cw.id_person;

答案 1 :(得分:0)

刚刚将三张桌子连在一起,就像这样:

SELECT
    t1.PersonName,
    t1.CarID,
    t2.WheelID
FROM People t1
LEFT JOIN Cars t2
    ON t1.CarID = t2.ID
LEFT JOIN Wheels t3
    ON t2.WheelID = t3.ID;