SQL查询列更新

时间:2013-03-18 16:33:03

标签: sql postgresql

+-------------------------------+
| id  subscriber       package  |
+-------------------------------+
| 1   5553288          heart    |
| 2   4443365          love     |
| 3   5553288          love     |
| 4   3332353          love     |
| 5   5845569          tech     |
+-------------------------------+

我想更新此表。

如果订阅者仅注册了包love,我想将其更改为heart

如果订阅者有包love& heart。我想删除love的行,并留下heart行。

我尝试使用此

UPDATE subscriber
SET package=`heart
WHERE package=`love`

`

它不会工作,因为有两个包中的订阅者

1 个答案:

答案 0 :(得分:0)

一旦你的规范有了一个很好的选择声明,你已经完成了大部分的努力工作。即使您将整个事物用作where子句或作为派生表连接它,通常也可以从中创建DML语句。

-- If a subscriber has signed up for package love only, I'd like to change it to heart.
update MyTable
set package = 'heart'
where subscriber in (
        -- Get subscribers with only love
        select subscriber
        from MyTable
        group by subscriber
        -- This having clause will handle duplicate subscriptions to love
        having max(package) = min(package)
            and max(package) = 'love'
    );

-- And if a subscriber has package love & heart. I'd like to delete the row for love and leave them with the row for heart.
delete from MyTable
where package = 'love'
    and subscriber in (
        -- Get subscribers with heart
        select subscriber
        from MyTable
        where package = 'heart'
    )
    and subscriber in (
        -- Get subscribers with love
        select subscriber
        from MyTable
        where package = 'love'
    );