gpt4 book ai didi

postgresql - 解决问题的 SQL if 语句

转载 作者:行者123 更新时间:2023-11-29 14:12:29 25 4
gpt4 key购买 nike

我有这个选择

insert into test(t_name)
(select users.first_name || '_' || users.last_name
|| '_' || to_date($values.report_date, 'YYYY.MM.DD')
from users where users.id = $session.user_id)

如果 users.first_name/users.last_name 为 null 且 user_id=0 则我希望插入另一个字符串“admin”,否则我会收到错误消息,因为它违反了列 t_name 的非空约束。

p>

如有任何建议,我们将不胜感激。谢谢。

最佳答案

在 SELECT 部分使用 CASE:

insert into test (t_name) 
select case
when users.first_name is null and users.last_name is null and users.id=0 then 'admin'
else users.first_name || '_' || users.last_name || '_' || to_date($values.report_date,'YYYY.MM.DD')
end
from users
where users.id = $session.user_id

如果您提到的所有条件都必须为真或只是其中之一,这个问题(对我而言)并不清楚。根据您的需要,您应该将第一个 WHEN 部分中的 AND 更改为 OR

(请注意,对于 INSERT ... SELECT 语句,无需将 SELECT 包含在 () 中)

关于postgresql - 解决问题的 SQL if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9972734/

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