简体   繁体   English

postgres 中的条件 INSERT INTO 语句

[英]Conditional INSERT INTO statement in postgres

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');

But Postgres doesn't support IF statements without loading the PL/pgSQL extension.但是 Postgres 不支持不加载 PL/pgSQL 扩展的IF语句。 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'
);

It will insert the result of the select statement, and the select will only return a row if that customer does not exist.它将插入 select 语句的结果,如果该客户不存在, select只会返回一行。

As of 9.5 version of pgsql upsert is included, using INSERT ... ON CONFLICT DO UPDATE ...从 9.5 版本开始包含 pgsql upsert,使用INSERT ... ON CONFLICT DO UPDATE ...

The answer below is no longer relevant.下面的答案不再相关。 Postgres 9.5 was released a couple years later with a better solution.几年后,Postgres 9.5 发布了一个更好的解决方案。

Postgres doesn't have " upsert " functionality without adding new functions. Postgres 没有“ upsert ”功能而不添加新功能。
What you'll have to do is run the select query and see if you have matching rows.您需要做的是运行选择查询并查看是否有匹配的行。 If you do, then insert it.如果你这样做,然后插入它。

I know you're not wanting an upsert exactly, but it's pretty much the same.我知道你并不完全想要一个 upsert,但它几乎是一样的。

-- Use follwing format to insert data in any table like this -- -- 使用以下格式在任何表格中插入数据,就像这样 --

create table user ( user_id varchar(25) primary key, phone_num numeric(15), failed_login int not null default 0, Login time timestamp );创建表用户(user_id varchar(25) primary key, phone_num numeric(15), failed_login int not null default 0, Login time timestamp );

INSERT INTO USER(user_id, phone_num, failed_login, Login time) VALUES ('12345','123456789','3',' 2021-01-16 04:24:01.755'); INSERT INTO USER(user_id, phone_num, failed_login, Login time) VALUES ('12345','123456789','3','2021-01-16 04:24:01.755');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM