简体   繁体   English

加入表SQL Server

[英]Join tables SQL Server

I want to join two tables but I want the result set to only show matches that arent in the right side. 我想加入两个表,但我希望结果集只显示不在右侧的匹配项。

Example: 例:

LeftTable LeftTable

  • leftID | leftID | PK PK
  • value | 价值|

RightTable RightTable

  • rightID |PK rightID | PK
  • leftID |FK leftID | FK

    select l.value 选择l.value

    from LeftTable l 来自LeftTable l

    join RightTable r 加入RightTable r

    on l.leftID = r.leftID 在l.leftID = r.leftID

I know this wont give me what I want, but I am just trying to find out which items in the left table DO NOT appear in the right side byusing the leftID foreign key relationship. 我知道这不会给我我想要的东西,但我只想通过使用leftID外键关系找出左表中的哪些项目不会出现在右侧。

Any ideas? 有任何想法吗?

What if we do 如果我们做了什么

select LT.value
from LeftTable LT
left outer join RightTable RT
on LT.leftID = RT.leftID
Where RT.leftId is null

SO join will return all the matching as well as those rows which are in left but not in right. SO join将返回所有匹配以及左侧但不是右侧的行。 With where clause we only get those rows for which right table left id is null. 使用where子句,我们只获得右表left id为null的那些行。

You nearly have it, just a couple of minor changes - the join should be a LEFT JOIN, not an [INNER] JOIN, and you need to only return the rows where the right table is missing, ie its fields are NULL: 你几乎拥有它,只需要几个小的改动 - 连接应该是LEFT JOIN,而不是[INNER] JOIN,你需要只返回缺少右表的行,即它的字段为NULL:

SELECT T1.value
FROM LeftTable T1
LEFT JOIN RightTable T2
ON T1.leftID = T2.leftID
WHERE T2.leftID IS NULL

select * from LeftTable where leftID not in (select leftID from RightTable)

SELECT LeftID
FROM LeftTable 
    LEFT OUTER JOIN RightTable ON LeftTable.LeftID = RightTable.LeftID
WHERE RightTable.RightId IS NULL

An alternative using exists , as a preference to using where not in . exists替代使用,优先使用where not in exists where not in The left outer join with a check on the null state of the right is probably still optimal though. left outer join检查右边的空状态可能仍然是最佳的。

select
        left.*
    from
        LeftTable as left
    where
        not exists (
            select
                    *
                from
                    RightTable as right
                where
                    right.RightID = left.LeftID
            )

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

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