postgres中的条件INSERT INTO语句 [英] Conditional INSERT INTO statement in postgres

查看:424
本文介绍了postgres中的条件INSERT INTO语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为模拟航空公司的预订数据库编写预订过程,而我真正想做的是这样的事情:

I'm writing a booking procedure for a mock airline booking database and what I really want to do is something like this:

IF EXISTS (SELECT * FROM LeadCustomer 
    WHERE FirstName = 'John' AND Surname = 'Smith') 
THEN
   INSERT INTO LeadCustomer (Firstname, Surname, BillingAddress, email) 
   VALUES ('John', 'Smith', '6 Brewery close,
            Buxton, Norfolk', 'cmp.testing@example.com');

但是Postgres不支持 IF 语句而不加载PL / pgSQL扩展。我想知道是否有某种方法可以做到这一点,或者在这一步中是否仅需要某些用户交互?

But Postgres doesn't support IF statements without loading the PL/pgSQL extension. I was wondering if there was a way to do some equivalent of this or if there's just going to have to be some user interaction in this step?

推荐答案

该特定命令可以这样完成:

That specific command can be done like this:

insert into LeadCustomer (Firstname, Surname, BillingAddress, email)
select 
    'John', 'Smith', 
    '6 Brewery close, Buxton, Norfolk', 'cmp.testing@example.com'
where not exists (
    select * from leadcustomer where firstname = 'John' and surname = 'Smith'
);

它将插入select语句的结果和 select 仅在该客户不存在时返回一行。

It will insert the result of the select statement, and the select will only return a row if that customer does not exist.

这篇关于postgres中的条件INSERT INTO语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆