【问题标题】:how to update column with row number in group by result in MySQL如何在MySQL中按结果更新具有行号的列
【发布时间】:2020-09-21 08:57:43
【问题描述】:

样本数据:

id  |  room_id  |  seat_num
----------------------------------
1   |   1      |  null
2   |   1      |  null
3   |   2      |  null
4   |   2      |  null

需求数据:

id  |  room_id  |  seat_num
----------------------------------
1   |   1      |  1
2   |   1      |  2
3   |   2      |  1
4   |   2      |  2

在 MySQL 5.7 中如何编写 sql 将房间座位号更新为序列号?房间的座位是2-20。

【问题讨论】:

    标签: mysql sql sql-update inner-join window-functions


    【解决方案1】:

    一个选项使用更新/连接语法。在 MySQL 5.7 中,窗口函数不可用,您可以使用相关子查询来模拟 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

    编号 |房间号 |座位号 :- | ------: | :-------- 1 | 1 | 1 2 | 1 | 2 3 | 2 | 1 4 | 2 | 2

    【讨论】:

    • 在有 70000+ 行的数据库中非常慢。 @GMB
    • @Dolphin:确保您在room_id, id 上有一个索引,这可能会有所帮助。底线:如果您想要高效的排名功能,请考虑升级到 MySQL 8.0...
    猜你喜欢
    • 2020-09-30
    • 1970-01-01
    • 2014-07-18
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多