MySQL - How to get a list of values in Table A that don't exist in Table B?

后端 未结 3 477
借酒劲吻你
借酒劲吻你 2021-01-26 07:51
**Table A**
1
2
3
4
5
6


**Table B**
2
3
5

How can I select for entry IDs that only exist in Table B? In this example, I\'m looking for a query th

相关标签:
3条回答
  • 2021-01-26 08:24

    Assuming the column is named 'id', either:

    SELECT *
    FROM tableA a
    WHERE NOT EXISTS (SELECT 1 FROM tableB WHERE id = a.id)
    

    or

    SELECT *
    FROM TableA
    WHERE id NOT IN (SELECT id FROM tableB)
    

    You will probably need to test to see which performs best. MySQL can be a bit unpredictable.

    0 讨论(0)
  • 2021-01-26 08:29

    Try

    select value from B where value not in (select value from A)
    

    to get values in B that are not in A.

    To get the opposite (values in A not in B) use

    select value from A where value not in (select value from B)
    
    0 讨论(0)
  • 2021-01-26 08:36

    This avoids IN + subquery:

    SELECT A.value FROM A
    LEFT OUTER JOIN B ON (A.value = B.value)
    WHERE B.value IS NULL
    

    Because IN (subquery) isn't optimized as it is executed for each found row in table A

    0 讨论(0)
提交回复
热议问题