postgres 中的条件 INSERT INTO 语句 [英] Conditional INSERT INTO statement in postgres
本文介绍了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 1 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屋!
查看全文