SQL Server How to query two tables with distinct values

ctehm74n  于 2023-04-10  发布在  其他
关注(0)|答案(1)|浏览(148)

I am trying to run a query that selects from table a and then from table b, but only returns data from table b that did not match an ID in table a. I'm currently using the union function but not sure where to go from here.

Table 1:

ID
---
1
2

Table 2:

ID
---
1
2

Query

Select
ID
1
2
From Table_1
Union
Select
ID
1
2
From Table_2

Thanks in advance!

I have tried using select distinct and except with no success.

bn31dyow

bn31dyow1#

You're on the right track, but I think you'll need to join table a and b to find out what is in b that isn't in a.

SELECT * FROM Table_1
UNION
SELECT * FROM (
    SELECT B.*
    FROM Table_2 B
    LEFT JOIN Table_1 A
        ON B.ID = A.ID
    WHERE A.ID IS NULL
)

The nested query will select only the records from Table_2 that didn't have a corresponding record in Table_1.

相关问题