Having trouble with this simple SQL Select statement

让人想犯罪 __ 提交于 2019-12-13 03:13:43

问题


I have two tables, A and B.

Both have the exact same columns.

I need to select all the items in TableA that ARE NOT in TableB.

This is intersection, right? How can I do this?


回答1:


assuming TableA and TableB have a primary key of name id.

select TableA.* 
  from TableA 
left outer join TableB on TableB.id = TableA.id
where TableB.id is null;

This will find all entries where table b does not have an instance of table a's id.




回答2:


You could use the EXISTS clause

SELECT * FROM TableA
WHERE NOT Exists
(
SELECT Column1 FROM TableB 
WHERE TableA.Column1 = Table2.Column1 
AND TableA.Column2 = Table2.Column2 
....
)

Replace .... with the rest of the columns in the two tables.




回答3:


SELECT ColumnA, ColumnB
FROM TableA
EXCEPT
SELECT ColumnA, ColumnB
FROM TableB



回答4:


You have your terminology wrong. The intersection would be the rows that are in both Table A and Table B. What you are actually looking for is the relative complement of A and B. To get a relative complement you want to do an antijoin:

SELECT * FROM TableA EXCEPT SELECT * FROM TableB.



回答5:


or NOT IN

SELECT *
FROM TableA
WHERE TableA.Id NOT IN (SELECT TableB.Id FROM TableB)


来源:https://stackoverflow.com/questions/1430515/having-trouble-with-this-simple-sql-select-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!