Fastest check if row exists in PostgreSQL

前端 未结 8 1318
有刺的猬
有刺的猬 2020-11-28 19:20

I have a bunch of rows that I need to insert into table, but these inserts are always done in batches. So I want to check if a single row from the batch exists in the table

8条回答
  •  爱一瞬间的悲伤
    2020-11-28 19:50

    INSERT INTO target( userid, rightid, count )
      SELECT userid, rightid, count 
      FROM batch
      WHERE NOT EXISTS (
        SELECT * FROM target t2, batch b2
        WHERE t2.userid = b2.userid
        -- ... other keyfields ...
        )       
        ;
    

    BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)

    INSERT INTO target( userid, rightid, count )
    SELECT userid, rightid, count 
    FROM batch
        ;
    

    will do exactly what you want: either it succeeds, or it fails.

提交回复
热议问题