【问题标题】:How to use exists condition in select query in postgresql?如何在 postgresql 的选择查询中使用存在条件?
【发布时间】:2021-06-07 01:42:54
【问题描述】:

我想检查 emp_id 和 date 是否已经存在于 bill_item 和 bill_item_temp 表中?如果不存在,那么我必须插入?

s = CONN.cursor()                 
query = """insert into bill_item (id,product_name,price,create_date,emp_id)
           select %s,%s,%s,%s,%s where not exists ( select 1 from bill_item where emp_id = %s and 
           select 1 from bill_item_ref where emp_id = %s);"""
s.execute(query,(id,product_name,price,create_date,emp_id,)); 

表:bill_item

id product_name price create_date                   emp_id
1  rice         10    2021-03-09 10:10:10.231321    12345
2  tea          10    2021-03-09 08:10:10.231321    22345

表:bill_item_temp

id product_name   price create_date                   emp_id
1  drinks         10    2021-03-09 10:10:10.231321    67345
2  snacks         10    2021-03-09 08:10:10.231321    92345

【问题讨论】:

  • 与您的问题无关,但是:Postgres 9.1 是no longer supported,您应该尽快计划升级。
  • 您能否提供一个替代解决方案,说明如何同时使用存在来检查 2 个选择查询

标签: python sql postgresql postgresql-9.1 exists


【解决方案1】:

此查询中缺少FROM 子句:

select %s,%s,%s,%s,%s where not exists(...)

SELECT 语句在这里的语法不正确:

where not exists ( select 1 from bill_item where emp_id = %s and 
                   select 1 from bill_item_ref where emp_id = %s);

两个SELECT 语句之间不能有AND。

要么使用UNION/UNION ALL,要么使用单独的EXISTS 用于单独的SELECT 语句。

这就是你可以使用UNION ALL的方法:

where not exists ( select 1 from bill_item where emp_id = %s UNION ALL 
                   select 1 from bill_item_ref where emp_id = %s);

这就是您可以将单独的EXISTS 用于单独的SELECT 语句的方式:

where not exists (select 1 from bill_item where emp_id = %s) and
      not exists (select 1 from bill_item_ref where emp_id = %s);

【讨论】:

  • 能否请您使用 union 给我代码.. 我是新手,我不知道如何使用
  • @pythoncoder 这取决于您的用例。您希望两个条目都存在吗?如果bill_item 中有条目但bill_item_ref 中缺少条目(反之亦然),会发生什么?
  • 任何一个表都有记录意味着(存在)意味着不应该发生插入。
  • @pythoncoder 我已经更新了我的答案以包括UNION ALL。
  • 这是一个 Python 异常。您可以尝试直接在 Postgres 中执行此查询吗?
猜你喜欢
  • 1970-01-01
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
相关资源
最近更新 更多