有条件地根据其他更新结果更新行

时间:2014-11-08 11:25:11

标签: mysql sql-update

在我的Mysql数据库中,我有一个数据表,如下所示

id  | id_fk  | name   | address  | city  | priority | status |
--------------------------------------------------------------
1   | 1      | name1  | address1 | city1 |          | active |
2   | 2      | name2  | address2 | city2 | primary  | active |
3   | 1      | name3  | address3 | city3 | primary  | active |
4   | 1      | name4  | address4 | city4 |          | active |
5   | 1      | name5  | address5 | city5 |          | active |
6   | 3      | name6  | address6 | city6 | primary  | active |
--------------------------------------------------------------

此处,id是行ID,id_fk是另一个表的引用。 status是数据状态。如果数据已删除,则为deletedpriority用于引用默认地址。

我的问题是,

如果我用id = 3删除地址,则'id_fk = 1'将没有任何优先级地址。我想将“id = 3”的状态更改为deleted,并将“id_fk = 1”中任意一个地址的priority设置为primary

简单UPDATE查询不会这样做。有没有办法做到这一点?预先感谢。

1 个答案:

答案 0 :(得分:1)

有两种UPDATE查询可以做到这一点:

UPDATE myTable SET status = 'deleted' WHERE id = 3
;
UPDATE myTable as a, 
(SELECT id_fk, max(id) 
  FROM myTable 
    WHERE id_fk = 1 
    AND status NOT IN ('deleted') 
  GROUP BY id_fk
) as b
SET a.priority = 'primary' 
WHERE a.id_fk = 1 
AND a.id = b.id