简体   繁体   English

如何对表中的行进行排序并获取行位置?

[英]How to sort rows in a table and fetch row positions?

Consider the following table structure: 考虑以下表结构:

id    name     rank    position
-------------------------------
1     Steve    5        0
2     David    3        0 
3     Helen    9        0 
4     Mark    15        0

I need a fast algorithm to rate these rows by rank column and store the "position" of each row in position field in realtime. 我需要一种快速算法来按rank对这些行进行评分,并将每行的“位置”实时存储在position字段中。

Now I have a brutal solution: 现在我有一个残酷的解决方案:

SELECT * FROM table ORDER BY rank DESC

And then fetch the result in a loop and update every row filling the position column. 然后循环获取结果,并更新填充位置列的每一行。 But what If I'd have thousands of entries? 但是,如果我有成千上万的条目怎么办? How can I optimize it? 我该如何优化?

I answered a very similar question specific to MySQL a few days ago: 我几天前回答了一个非常类似的针对MySQL的问题:

Automate MySQL fields (like Excel) 自动执行MySQL栏位(例如Excel)

The trick is not to store the column in the database but to calculate it dynamically when you fetch the results. 诀窍不是将列存储在数据库中,而是在获取结果时动态地对其进行计算。 Alternatively you could use triggers to update the column every time you make an insert, update or delete. 另外,您可以在每次插入,更新或删除时使用触发器来更新列。

Pick one: 选一个:

WITH t AS
(
SELECT 
  ROW_NUMBER() OVER (ORDER BY rank) as RowNum
  ,RANK() OVER (ORDER BY rank) as RankNum
  ,DENSE_RANK() OVER (ORDER BY rank) as DenseRankNum
  , * 
FROM table
)
UPDATE t set position = RankNum
--UPDATE t set position = RowNum
--UPDATE t set position = DenseRankNum
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM