SQL: Select Keys that doesn't exist in one table

前端 未结 6 741
刺人心
刺人心 2021-01-11 11:24

I got a table with a normal setup of auto inc. ids. Some of the rows have been deleted so the ID list could look something like this:

(1, 2, 3, 5, 8,

6条回答
  •  旧时难觅i
    2021-01-11 12:04

    What about using a left join ; something like this :

    select second_table.id
    from second_table
        left join first_table on first_table.id = second_table.id
    where first_table.is is null
    


    You could also go with a sub-query ; depending on the situation, it might, or might not, be faster, though :

    select second_table.id
    from second_table
    where second_table.id not in (
        select first_table.id
        from first_table
    )
    

    Or with a not exists :

    select second_table.id
    from second_table
    where not exists (
        select 1
        from first_table
        where first_table.id = second_table.id
    )
    

提交回复
热议问题