案例,在单个查询中选择和更新

时间:2016-11-25 12:56:04

标签: sql postgresql

我正在尝试执行以下操作,但是我在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

5 个答案:

答案 0 :(得分:3)

如果您使用可写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定义为数字数据类型(integerbigint或类似内容),则应使用where personid = 276178。千万不要在数字上加单引号。

答案 1 :(得分:3)

您可以使用with语句删除或更新一个查询中的行,例如:

with delete_person as (
    delete from person_net_contacts
    where personid = '276178'
    and createts = endts
    returning 'deleted'::text, createts, endts
),
update_person as (
    update person_net_contacts
    set endts = current_timestamp
    where personid = '276178'
    and createts is distinct from endts
    returning 'updated'::text, createts, endts
)
select *
from delete_person
union all
select *
from update_person;

答案 2 :(得分:0)

IF EXISTS(SELECT 1 FROM person_net_contacts WHERE personid='276178' AND DATEDIFF(DAY,createts,endts) = 0)
BEGIN
  DELETE FROM person_net_contacts where personid='276178'
END
ELSE
BEGIN
  UPDATE person_net_contacts SET endts = current_timestamp where personid='276178'
END

答案 3 :(得分:0)

您不能像这样混合SELECTDELETEUPDATECASE。我假设你想这样做:

DELETE FROM person_net_contacts
WHERE personid='276178' AND createts=endts;

UPDATE person_net_contacts
SET endts = current_timestamp
WHERE personid='276178' AND createts!=endts;
-- the last condition only kicks in if you run the two statements in a different order

答案 4 :(得分:0)

这种操作混合(SELECT和DELETE,UPDATE)不是SQL表达式的一部分。但是,您可以使用正确的条件独立运行SELECT,DELETE和UPDATE操作:

所有选择字段必须是返回某个值的表达式:UPDATE或DELETE操作不适用于此。

SELECT createts, endts
FROM person_net_contacts
WHERE personid='276178';

在createts = endts

时删除记录
DELETE FROM person_net_contacts where personid='276178' and createts = endts;

在createts<>时更新记录endts(可以省略最后一个条件,更新仅影响上一个命令中未删除的记录)

UPDATE person_net_contacts SET endts = current_timestamp where personid='276178' and createts <> endts;