微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在postgres中不存在

如何解决在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'))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。