【问题标题】:mysql select counter of current position [duplicate]mysql选择当前位置的计数器[重复]
【发布时间】:2020-10-05 08:49:12
【问题描述】:

有这样一张桌子

+--------+------------+
| orderID | productID |
+--------+------------+
|    100 |         10 |
|    100 |         11 |
|    101 |         10 |
|    101 |         11 |
|    101 |         12 |
+--------+------------+

我需要添加第三列,即产品当前位置的计数器。 喜欢:

+--------+------------+--------------+
| orderID | productID | currentIndex | 
+--------+------------+--------------+
|    100 |         10 |      1       |
|    100 |         11 |      2       |
|    101 |         10 |      1       |
|    101 |         11 |      2       |
|    101 |         12 |      3       |
+--------+------------+--------------+

可以帮帮我吗?

我现在有这个查询:

SELECT orderID, productID
FROM orders;

【问题讨论】:

    标签: mysql sql select window-functions


    【解决方案1】:

    如果您运行的是 MySQL 8.0,`row_number() 会完全按照您的要求执行:

    select orderid, productid, 
        row_number() over(partition by orderid order by productid) currentindex
    from orders;
    

    在早期版本中,备选方案是用户变量或相关子查询。我将推荐第二个选项 - 用户变量使用起来相当棘手,现在正式计划在未来弃用:

    select orderid, productid, 
        (select count(*) from orders o1 where o1.orderid = o.orderid and o1.productid <= o.productid) currentindex
    from orders o;
    

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多