简体   繁体   中英

SQL (MS-Access) - LEFT JOIN to show records in left table not in right table

I have 2 tables: A has 400000 records and B has 350000 records approximately.

I'm doing a LEFT JOIN to show the difference between both tables but the query returns 100000 approx.

This is my Not-In query:

SELECT *
FROM TableA LEFT JOIN TableB
ON TableA.[ID] = TableB.[ID]
WHERE (TableB.[ID] is null)

Is there something wrong or is it possible that the query returns more than the difference between the tables? Thanks

You query shows rows from table A that do not have a match in table B. If you want the differences you also need rows from Table B that do not exist in Table A. You can do this with a union

SELECT *
   FROM TableA 
   LEFT JOIN TableB ON TableA.[ID] = TableB.[ID]
   WHERE (TableB.[ID] is null)
Union All
SELECT *
   FROM TableB 
   LEFT JOIN TableA ON TableB.[ID] = TableA.[ID]
   WHERE (TableA.[ID] is null)

EDIT: This assumes similar table structures. You may need to use column names rather than * in the select clause.

Other than the difference, you might pull some rows from TableB where ID is really null, as equality doesn't work for null values.

So the correct way, as stated in the other answer, is to set the NULL condition as part of the ON clause, not WHERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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