gpt4 book ai didi

sql - PostgreSQL:如果不存在则插入,如果存在则返回ID

转载 作者:行者123 更新时间:2023-12-05 07:01:28 24 4
gpt4 key购买 nike

如果没有 IP 地址,以下查询将插入 IP 地址并返回 ID。

WITH variables AS (
SELECT '1.1.1.2'::inet AS ip
)
INSERT INTO globals.ips (ip)
SELECT v.ip
FROM variables AS v
WHERE NOT EXISTS (
SELECT i.global_ip_id
FROM globals.ips AS i
WHERE i.ip = v.ip
)
RETURNING global_ip_id

但是,当该值已存在于数据库中时,它不会返回 ID。

当值已经存在时,如何获取 ID?


我正在运行 PostgreSQL 12。

最佳答案

WITH variables AS (
SELECT '1.1.1.2'::inet AS ip
), wt0 as (
INSERT INTO globals.ips (ip)
SELECT v.ip
FROM variables AS v
WHERE NOT EXISTS (
SELECT i.global_ip_id
FROM globals.ips AS i
WHERE i.ip = v.ip
)
RETURNING global_ip_id
)
SELECT global_ip_id FROM wt0
UNION
SELECT id FROM globals.ips WHERE ip = 'SOMETHING';

关于sql - PostgreSQL:如果不存在则插入,如果存在则返回ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63817389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com