select a value where it doesn't exist in another table

后端 未结 6 1558
忘掉有多难
忘掉有多难 2021-02-04 23:09

I have two tables

Table A:

ID
1
2
3
4

Table B:

ID
1
2
3

I have two requests:

  • I want to
6条回答
  •  爱一瞬间的悲伤
    2021-02-04 23:59

    You could use NOT IN:

    SELECT A.* FROM A WHERE ID NOT IN(SELECT ID FROM B)
    

    However, meanwhile i prefer NOT EXISTS:

    SELECT A.* FROM A WHERE NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID)
    

    There are other options as well, this article explains all advantages and disadvantages very well:

    Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?

提交回复
热议问题