问题描述
Update table1 set status='open' where user='test' order by id DESC
我想用 where 条件更新最后一行
解决方法
您可以使用窗口函数row_number()获取id降序的第一行。
with cte as
(
select *,row_number()over(order by id desc)rn from table1
)
Update cte set status='open' where user='test' and rn=1
或者您可以使用子查询来实现相同的结果:
UPDATE table1 SET status='open'
WHERE ID=(SELECT MAX(ID)FROM table1 where user='test') and user='test'
,
为了找到您想要的记录,您必须首先找到您想要的记录,然后在表中更改该记录。为此,您需要创建一个临时表并将所需的记录放入其中,然后使用获得的信息更新该表。
--Container to Insert Id which are to be iterated
Declare @temp1 Table
(
ID int
)
--Container to Insert records in the inner select for final output
Insert into @temp1
SELECT top 1 t.id FROM table1 t
WHERE t.user = 'test'
order by t.id desc
-- Keep track of @temp1 record processing
Declare @columnID int
Declare @columnValue varchar(100)
Begin
Set @columnID=(Select Top 1 id From @temp1)
Set @columnValue = 'open'
UPDATE table1 SET status = @columnValue WHERE id = @columnID
Delete @temp1 Where ID=@columnID
End
,
这应该可行,假设 DBMS 是 MySQL
UPDATE table1
SET status = "open"
WHERE id in
(SELECT *
FROM
(SELECT id
FROM table1
WHERE USER = "test"
ORDER BY id DESC
LIMIT 1) tmp_tbl);