Fastest check if row exists in PostgreSQL

前端 未结 8 1303
有刺的猬
有刺的猬 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:49

    select true from tablename where condition limit 1;
    

    I believe that this is the query that postgres uses for checking foreign keys.

    In your case, you could do this in one go too:

    insert into yourtable select $userid, $rightid, $count where not (select true from yourtable where userid = $userid limit 1);
    

提交回复
热议问题