[英]how to update column with row number in group by result in MySQL
Sample Data:样本数据:
id | room_id | seat_num
----------------------------------
1 | 1 | null
2 | 1 | null
3 | 2 | null
4 | 2 | null
Desire Data:愿望数据:
id | room_id | seat_num
----------------------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 2 | 2
how to write a sql to update the room seat number to serial num in MySQL 5.7?在MySQL 5.7中如何写一个sql更新房间座位号为序号? the room's seat is from 2-20.
房间的座位是2-20。
One option uses the update/join syntax.一种选择使用更新/加入语法。 In MySQL 5.7, where window functions are not available, you can emulate
row_number()
with a correlated subquery (which is somehow safer than user variables):在 MySQL 5.7 中,window 函数不可用,您可以使用相关子查询模拟
row_number()
(这比用户变量更安全):
update mytable t
inner join (
select id,
(select count(*) from mytable t1 where t1.room_id = t.room_id and t1.id <= t.id) rn
from mytable t
) t1 on t1.id = t.id
set t.seat_num = t1.rn
Demo on DB Fiddle : DB Fiddle 演示:
id | room_id | seat_num :- | ------: | :------- 1 | 1 | 1 2 | 1 | 2 3 | 2 | 1 4 | 2 | 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.