我希望向表中添加一个列,该表按其他值描述行的顺序。例如,我有以下数据:
popularity = 1, id =1
popularity = 1, id =2
popularity = 2, id =3
popularity = 3, id =4
popularity = null, id=5我需要一个查询来获得以下内容:
popularity = 1, id =1, newOrder = 4
popularity = 1, id =2, newOrder = 3
popularity = 2, id =3, newOrder = 2
popularity = 3, id =4, newOrder = 1
popularity = null, id=5, newOrder = 5这里适用的规则是:-在相同的受欢迎程度上,按id排序-最高的受欢迎度是新顺序的第一个,空的受欢迎度在新的顺序上是最低的。
我试图这样做,因为表有数百万行,而按受欢迎程度和使用偏移量进行分页非常慢。因此,有了这个新的顺序,我就可以做id > page*page_amount之类的事情了。
设置此值的update查询非常好,因为带有偏移量的select查询非常慢。
谢谢
发布于 2019-08-14 19:45:46
我找到了解决这个问题的方法,如果有人需要的话:
SET @actual_id := 0;
UPDATE file
SET main_listing_page = (@actual_id:=@actual_id+1)
WHERE status = 1 And title_date is not null
ORDER BY popularity desc, id desc;它使用一个动态变量,该变量在每一步中都会发生变化。
发布于 2019-08-14 17:01:39
我想你想:
select . . .,
row_number() over (order by (popularity is not null) desc, popularity desc, id) as newOrder
from t;发布于 2019-08-14 18:23:02
如果您的MySql版本不允许窗口函数:
update tablename t
inner join (
select
t.id,
(select count(*) from tablename
where
coalesce(popularity, 0) > coalesce(t.popularity, 0)
or
(coalesce(popularity, 0) = coalesce(t.popularity, 0) and id >= t.id)
) counter
from tablename t
) c on c.id = t.id
set t.neworder = c.counter;见演示。
对于MySql 8.0+:
update tablename t
inner join (
select
t.id,
row_number() over (order by coalesce(popularity, 0) desc, id desc) counter
from tablename t
) c on c.id = t.id
set t.neworder = c.counter;见演示。
结果:
| id | popularity | neworder |
| --- | ---------- | -------- |
| 1 | 1 | 4 |
| 2 | 1 | 3 |
| 3 | 2 | 2 |
| 4 | 3 | 1 |
| 5 | | 5 |https://stackoverflow.com/questions/57499053
复制相似问题