TSQL左连接和内连接

时间:2018-03-09 14:03:07

标签: tsql left-join inner-join

给出以下样本数据:

CREATE TABLE People(PeopleID int, Name varchar(10))
INSERT INTO People VALUES(1, 'Chris')
INSERT INTO People VALUES(2, 'Cliff')
INSERT INTO People VALUES(3, 'Heather')

CREATE TABLE Things(ThingID int, ThingName varchar(10))
INSERT INTO Things VALUES(14, 'Bike')
INSERT INTO Things VALUES(17, 'Trailer')
INSERT INTO Things VALUES(18, 'Boat')

CREATE TABLE PeopleThings(PeopleID int, ThingID int)
INSERT INTO PeopleThings VALUES(1, 18)
INSERT INTO PeopleThings VALUES(2, 14)

...以及以下查询:

SELECT P.Name,
     T.ThingName
FROM People P
    LEFT OUTER JOIN PeopleThings PT ON P.PeopleID = PT.PeopleID
    INNER JOIN Things T ON PT.ThingID = T.ThingID

我希望看到以下结果:

|Name      |ThingName |
-----------------------
|Chris     |Boat      |
-----------------------
|Cliff     |Bike      |
-----------------------
|Heather   |(null)    |
-----------------------

我想要一个PEOPLE表中每个人的列表,以及他们拥有的东西的名字(或者如果他们拥有任何东西)。我知道问题出在我的JOIN中,但我不理解/看到哪里。请帮忙。

2 个答案:

答案 0 :(得分:1)

你已经有了答案,但我正在研究它 INNER JOIN Things T ON PT.ThingID打破了左连接

您可以保留inner join,但可以更改on的顺序 这可能比2 left join更有效。

declare @People TABLE (PeopleID int primary key, Name varchar(10));
INSERT INTO @People VALUES
       (1, 'Chris')
     , (2, 'Cliff')
     , (3, 'Heather');

declare @Things TABLE (ThingID int primary key, ThingName varchar(10))
INSERT INTO @Things VALUES
       (14, 'Bike')
     , (17, 'Trailer')
     , (18, 'Boat');

declare @PeopleThings TABLE (PeopleID int, ThingID int, primary key (PeopleID, ThingID));
INSERT INTO @PeopleThings VALUES
       (1, 18)
     , (1, 17)
     , (2, 14);

SELECT P.Name, T.ThingName
FROM @People P
LEFT JOIN @PeopleThings PT   
     JOIN @Things T 
       ON PT.ThingID = T.ThingID 
  ON P.PeopleID = PT.PeopleID
order by P.Name, t.ThingName;

Name       ThingName
---------- ----------
Chris      Boat
Chris      Trailer
Cliff      Bike
Heather    NULL

也可以使用正确的联接

SELECT P.Name, T.ThingName
FROM @PeopleThings PT
JOIN @Things T 
  ON PT.ThingID = T.ThingID 
right join @People P 
  ON P.PeopleID = PT.PeopleID 
order by P.Name, t.ThingName;

答案 1 :(得分:0)

这将解决您的疑问:

var mergedStyles = (0, _simpleAssign2.default)({
    display: 'inline-block',
    color: svgIcon.color, //  <-- This one!
    fill: this.state.hovered ? onColor : offColor,
    height: 24,
    width: 24,
    userSelect: 'none',
    transition: _transitions2.default.easeOut()
  }, style);