這在1至零或多個出現,其中許多具有FK。
兩種方法
秩序on
把outer
參加最後
不幸你改變表名。我會用後面的名字。
declare @TableD TABLE (PeopleID int primary key, Name varchar(10));
INSERT INTO @TableD VALUES
(1, 'Chris')
, (2, 'Cliff')
, (3, 'Heather');
declare @TableA TABLE (ThingID int primary key, ThingName varchar(10))
INSERT INTO @TableA VALUES
(14, 'Bike')
, (17, 'Trailer')
, (18, 'Boat');
declare @TableF TABLE (PeopleID int, ThingID int, primary key (PeopleID, ThingID));
INSERT INTO @TableF VALUES
(1, 18)
, (1, 17)
, (2, 14);
SELECT D.Name, A.ThingName
FROM @TableD D
LEFT JOIN @TableF F
JOIN @TableA A
ON A.ThingID = F.ThingID
ON F.PeopleID = D.PeopleID
order by D.Name, A.ThingName;
SELECT D.Name, A.ThingName
FROM @TableF F
JOIN @TableA A
ON A.ThingID = F.ThingID
right join @TableD D
ON D.PeopleID = F.PeopleID
order by D.Name, A.ThingName;
Name ThingName
---------- ----------
Chris Boat
Chris Trailer
Cliff Bike
Heather NULL
這並沒有給出表D上的所有行(即你稱之爲c) – Paparazzi 2018-03-09 15:09:25