[英]Conditional INSERT INTO statement in postgres
我正在為模擬航空公司預訂數據庫編寫預訂程序,我真正想做的是這樣的:
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 不支持不加載 PL/pgSQL 擴展的IF
語句。 我想知道是否有一種方法可以做一些類似的事情,或者是否只需要在這一步中進行一些用戶交互?
該特定命令可以這樣完成:
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
只會返回一行。
從 9.5 版本開始包含 pgsql upsert,使用INSERT ... ON CONFLICT DO UPDATE ...
下面的答案不再相關。 幾年后,Postgres 9.5 發布了一個更好的解決方案。
Postgres 沒有“ upsert ”功能而不添加新功能。
您需要做的是運行選擇查詢並查看是否有匹配的行。 如果你這樣做,然后插入它。
我知道你並不完全想要一個 upsert,但它幾乎是一樣的。
-- 使用以下格式在任何表格中插入數據,就像這樣 --
創建表用戶(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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.