我需要使用 ORDER BY 获取某些行的计数。
如何获取行数 orderId = 50 之前是什么 (我看到答案是3,但我需要mysql查询如何得到它)
我有这样的 mysql 查询:
select c.id as customerId, o.id as orderId from orders o
inner join customers c on (c.id=o.customerId)
order by c.id asc, o.id desc
此查询输出:
customerId orderId
19 36
19 35
19 34
31 50
31 49
31 48
53 73
53 72
最佳答案
<强> SQL DEMO
SELECT Max(rn)
FROM (
select customerId,
orderId ,
@row := if( orderid = 50,
null,
@row + 1 ) as rn
from orders o
cross join ( SELECT @row := 0 ) as vars
order by customerId asc, orderId desc
) t
是否可以使用row_number
SELECT MIN(rn) - 1 as cnt
FROM (
select customerId,
orderId ,
row_number() over (order by customerId asc, orderId desc ) as rn
from orders
) t
WHERE orderId = 50;
关于mysql - 如何使用 ORDER BY 计算行数直到某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58210074/