问题描述
我想检查 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);