我正在尝试执行以下操作,但在 DELETE FROM 时出现错误,知道为什么吗?那么我如何检查 person_net_contacts 中的 createts=endts 对于某些 persondID 是否为真然后删除...否则更新...
SELECT
createts, endts,
CASE WHEN createts = endts
THEN DELETE FROM person_net_contacts where personid='276178';
ELSE UPDATE person_net_contacts SET endts = current_timestamp
WHERE personid='276178';
FROM person_net_contacts
最佳答案
如果您使用可写 CTE,您可以通过单个查询来完成此操作:
with to_check as (
SELECT personid, createts, endts, createts = endts as delete_this
WHERE personid = '276178'
FROM person_net_contacts
), deleted as (
delete from person_net_contacts
where personid = (select personid
from to_check
where delete_this)
)
update person_net_contacts pnc
SET endts = current_timestamp
from to_check tc
where tc.personid = pnc.personid
and not tc.delete_this;
第一个 CTE 从表中选择行并创建一个标志,告诉我们是否应该删除该行。然后,第二个 CTE 会根据该标志删除行,如果需要,最后的语句会更新该行。
假设 personid
是唯一的,这也适用于多行。
您还应该将数字与数字进行比较 '276178'
是一个字符串值,而不是数字。如果 personid
被定义为数字数据类型(integer
、bigint
或类似的东西),您应该使用 where personid = 276178
。永远不要在数字周围加上单引号。
关于sql - 在单个查询中区分大小写、选择和更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40805626/