SQL Server table join

I want to join two tables, but I want only the arent matches on the right side to be displayed in the result set.

Example:

Lefttable

  • leftID | PC
  • value |

Righttable

  • rightID | PK
  • leftID | Fk

    select l.value

    from LeftTable l

    attach RightTable r

    on l.leftID = r.leftID

I know that this will not give me what I want, but I'm just trying to figure out which elements in the left table are NOT displayed on the right side using the foreign key relation leftID.

Any ideas?

+3
source share
5 answers

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 , , , . where , .

+11

, - 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
+5

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

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

, exists, where not in. left outer join , , .

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

Source: https://habr.com/ru/post/1729441/


All Articles