【问题标题】:How to check if id existed in another table before we trigger insert query在我们触发插入查询之前如何检查 id 是否存在于另一个表中
【发布时间】:2017-10-26 09:25:57
【问题描述】:

my_Image 表格说明

name    characterVarying(30),
image    oid,
mime_type charactervarying(30)

pg_largeobject 表描述

loid oid

我的查询:

insert into myImage values('myImage', lo_from_bytea(999999,decode('RRRXFFDF','base64')),'jpg');

在我想在 postgres 中触发我的查询之前。我想确保在表pg_largeObject 中这个值 999999 不会出现在 postgres 中。所以你能帮我写我的插入语句吗?如果不存在那个 loid 那么只有我的插入语句应该触发。请帮助我在这里编写插入语句或存储过程。

【问题讨论】:

  • 你可以使用insert..select... where not exists(select where 99999),但它不会是原子的——如果你需要它稳定的高并发,使用UPSERT或者写一个带有异常处理的plpgsql...
  • 你能给我完整的查询吗?我是编写查询的新手。如果可能的话。我可以使用这个(选择 99999),因为这个 99999 是我们在这里手动提供的。有了这个,它会创建一个新行。
  • insert into myImage select 'myImage', lo_from_bytea(999999,decode('RRRXFFDF','base64')),'jpg' where not exists (select 'Ravi' from myImage where image=999999 );
  • 我在您的查询中没有理解这一点。 (从 myImage 中选择“Ravi”,其中 image=999999); Ravi 为什么来这里?请向我提供工作查询。
  • 放任何东西。人们一直在问为什么他们应该在where exists 中使用select null - 所以我明确使用任何东西 - 不为空

标签: sql postgresql stored-procedures


【解决方案1】:
insert into myImage select 'myImage', lo_from_bytea(999999,decode('RRRXFFDF','base64')),'jpg' 
where not exists (
  select null from pg_largeObject where loid=999999
);

请注意,select null 部分中的 NULL 无关紧要 - 如果行存在,则可以返回任何值。

还要注意这个解决方案在高并发系统上可能会失败,因为子查询不是原子的

【讨论】:

    【解决方案2】:

    Vao Tsun 回答,对 select 语句稍作修改:

    insert into myImage select 'myImage', lo_from_bytea(999999,decode('RRRXFFDF','base64')), 'jpg' where not exists (select * from pg_largeObject where loid=999999 );

    【讨论】:

    • 我修改了查询以满足您的需要,并在我的回答中提供了其他信息,请接受而不是自己回答
    猜你喜欢
    • 2022-12-20
    • 2014-01-07
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    相关资源
    最近更新 更多