在我的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
是数据状态。如果数据已删除,则为deleted
。 priority
用于引用默认地址。
我的问题是,
如果我用id = 3
删除地址,则'id_fk = 1'将没有任何优先级地址。我想将“id = 3”的状态更改为deleted
,并将“id_fk = 1”中任意一个地址的priority
设置为primary
。
简单UPDATE
查询不会这样做。有没有办法做到这一点?预先感谢。
答案 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