在postgres中不存在

问题描述

我正在使用postgres db,我试图在SQL下面执行以插入不存在的表中

我想先将数据插入表中,然后再检查是否存在,否则不要插入。

我希望简化查询,因为我将在带有pycopg2库的python代码中使用它

INSERT INTO T1 (a1,a2,a3,a4)
VALUES (123,'20e16411-b8f7',4,(SELECT u1 from T2 where u2 = 'test@test.com'))
WHERE NOT EXISTS (SELECT a3 
                  FROM TI 
                  WHERE a1 =123 
                    AND a2 = '20e16411-b8f7' 
                    AND a3 = 4 
                    AND a4 = (SELECT u1 from T2 where u2 = 'test@test.com'))

SQL Error [42601]: ERROR: syntax error at or near "WHERE" Position: 236

我在哪里语法上遇到了问题,但是,如果不能很好地纠正我的查询,我不确定这是否是实现我的逻辑的正确查询

If not exist (select * from t1 where <check>)
Begin
Insert
End

解决方法

我认为您想要<html> <head> </head> <body> <div class="survery-questions"> <form action=""> <div class="price-form"> <input name="price-1" type="text" placeholder="price 1" class="home-price-footer" id="input" required> </div> <div class="phone-form"> <input name="price-2" type="text" placeholder="price 2" class="home-price-footer" id="input" required> </div> <div class="email-form"> <input type="price-3" placeholder="price 3" class="home-price-footer" id="input" required> </div> <div class="price-form"> <input name="price-4" type="text" placeholder="price 4" class="home-price-footer" id="input" required> </div> <div class="phone-form"> <input name="price-5" type="text" placeholder="price 5" class="home-price-footer" id="input" required> </div> <div class="email-form"> <input type="price-6" placeholder="price 6" class="home-price-footer" id="input" required> </div> <div class="price-form"> <input name="price-7" type="text" placeholder="price 7" class="home-price-footer" id="input" required> </div> <div class="phone-form"> <input name="price-8" type="text" placeholder="price 8" class="home-price-footer" id="input" required> </div> <div class="email-form"> <input type="price-9" placeholder="price 9" class="home-price-footer" id="input" required> </div> </form> </div> </body> </html>

insert ... select
,

让数据库验证唯一性。在您关注的列上定义唯一约束:

create unique index unq_t1_a1_a2_a3_a4 on t1(a1,a2,a3,a4);

然后使用on conflict

insert into T1 (a1,a4)
    select 123,'20e16411-b8f7',4,t2.u1
    from T2
     where t2.u2 = 'test@test.com'
    on conflict (a1,a4) do nothing;
,

您不能在VALUES之后使用WHERE,这就是为什么会出现错误,在此查询中,您必须使用SELECT而不是VALUES,类似这样;

INSERT INTO T1 (a1,a4)
SELECT 123,(SELECT u1 from T2 where u2 = 'test@test.com')
WHERE NOT EXISTS (SELECT a3 
              FROM TI 
              WHERE a1 =123 
                AND a2 = '20e16411-b8f7' 
                AND a3 = 4 
                AND a4 = (SELECT u1 from T2 where u2 = 'test@test.com'))

相关问答

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