SQL 没有 ROW_NUMBER() 且分区依据的行数?玛丽亚数据库 10.1
SQL Number Rows without ROW_NUMBER() with Partition By ? MariaDB 10.1
我想这样做:
SELECT * , ROW_NUMBER() OVER (PARTITION BY Id ORDER BY score DESC, creationDate DESC) as num
FROM DB
ORDER BY score DESC, creationDate DESC
但在 MariaDB 10.1 中,因此 row_number 不可用。我设法做到了:
SELECT *, (@num:= @num + 1) AS num
from DB,
(SELECT @num:= 0 AS num1) AS c
order by score DESC, creationDate DESC
但我不知道如何放置分区,所以我可以为任何 Id 开始新的计数
(最终目的是按创建的数量排序)
谢谢
您可以将其表示为:
SELECT db.*,
(@rn := IF(@id = id, @rn + 1,
IF(@id := id, 1, 1)
)
) as num
from (SELECT db.*
FROM DB
ORDER BY id, score DESC, creationDate DESC
) db CROSS JOIN
(SELECT @rn := 0, @id := '') params;
注意:这使用子查询在 进行计算之前对行 进行排序。 MySQL 的较新的 8.0 之前版本需要这样做。不知道MariaDB是否真的需要它。
我想这样做:
SELECT * , ROW_NUMBER() OVER (PARTITION BY Id ORDER BY score DESC, creationDate DESC) as num
FROM DB
ORDER BY score DESC, creationDate DESC
但在 MariaDB 10.1 中,因此 row_number 不可用。我设法做到了:
SELECT *, (@num:= @num + 1) AS num
from DB,
(SELECT @num:= 0 AS num1) AS c
order by score DESC, creationDate DESC
但我不知道如何放置分区,所以我可以为任何 Id 开始新的计数 (最终目的是按创建的数量排序)
谢谢
您可以将其表示为:
SELECT db.*,
(@rn := IF(@id = id, @rn + 1,
IF(@id := id, 1, 1)
)
) as num
from (SELECT db.*
FROM DB
ORDER BY id, score DESC, creationDate DESC
) db CROSS JOIN
(SELECT @rn := 0, @id := '') params;
注意:这使用子查询在 进行计算之前对行 进行排序。 MySQL 的较新的 8.0 之前版本需要这样做。不知道MariaDB是否真的需要它。