SQL query to find record with ID not in another table

后端 未结 6 1596
眼角桃花
眼角桃花 2020-12-02 09:02

I have two tables with binding primary key in database and I desire to find a disjoint set between them. For example,

  • Table1 has columns (ID
6条回答
  •  醉梦人生
    2020-12-02 09:26

    Fast Alternative

    I ran some tests (on postgres 9.5) using two tables with ~2M rows each. This query below performed at least 5* better than the other queries proposed:

    -- Count
    SELECT count(*) FROM (
        (SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
    ) t1_not_in_t2;
    
    -- Get full row
    SELECT table1.* FROM (
        (SELECT id FROM table1) EXCEPT (SELECT id FROM table2)
    ) t1_not_in_t2 JOIN table1 ON t1_not_in_t2.id=table1.id;
    

提交回复
热议问题