更新MySQL表中的x行

时间:2019-04-27 00:00:58

标签: mysql

我有这张桌子:

___Units

|--------|------------|
| UNI_Id | UNI_Status |
|--------|------------|
|      1 |     active |
|      2 |     active |
|      3 |     active |
|      4 |     active |
|      5 |     active |
|      6 |     active |
|--------|------------|

仅当当前状态为inactive时,才能如何将最后创建的两行的状态更新为active

这是我尝试过的:

UPDATE ___Units SET UNI_Status='inactive' WHERE (
    SELECT * FROM ___Units ORDER BY UNI_Id DESC LIMIT 2
) sub
ORDER BY UNI_Id ASC

谢谢。

1 个答案:

答案 0 :(得分:0)

加入一个返回两个最高ID的子查询。

UPDATE ___Units AS u1
JOIN (
    SELECT UNI_Id
    FROM ___Units
    ORDER BY UNI_Id DESC
    LIMIT 2) AS u2 ON u1.UNI_Id = u2.UNI_Id
SET u1.UNI_Status = 'inactive'
WHERE u1.UNI_Status = 'active'