简体   繁体   English

SQL(MS-Access)-LEFT JOIN显示左表中的记录而不是右表中的记录

[英]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. 我有2个表:A大约有400000条记录,B大约有350000条记录。

I'm doing a LEFT JOIN to show the difference between both tables but the query returns 100000 approx. 我正在做一个LEFT JOIN,以显示两个表之间的差异,但查询返回约100000。

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 您查询显示表A中与表B中不匹配的行。如果需要差异,您还需要表B中表A中不存在的行。您可以通过并集来实现

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. 您可能需要在select子句中使用列名而不是*。

Other than the difference, you might pull some rows from TableB where ID is really null, as equality doesn't work for null values. 除了区别之外,您可能会从TableB中提取ID实际上为空的某些行,因为相等对空值不起作用。

So the correct way, as stated in the other answer, is to set the NULL condition as part of the ON clause, not WHERE 因此,如另一个答案所述,正确的方法是将NULL条件设置为ON子句的一部分,而不是WHERE

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

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