如何在postgresql的选择查询中使用存在条件?

问题描述

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

s = CONN.cursor()                 
query = """insert into bill_item (id,product_name,price,create_date,emp_id)
           select %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,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

解决方法

此查询中缺少 FROM 子句:

select %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);

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

对于单独的 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);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...