首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何制作描述元素顺序的列?

如何制作描述元素顺序的列?
EN

Stack Overflow用户
提问于 2019-08-14 16:59:53
回答 3查看 55关注 0票数 1

我希望向表中添加一个列,该表按其他值描述行的顺序。例如,我有以下数据:

代码语言:javascript
复制
popularity = 1, id =1
popularity = 1, id =2
popularity = 2, id =3
popularity = 3, id =4
popularity = null, id=5

我需要一个查询来获得以下内容:

代码语言:javascript
复制
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查询非常慢。

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-08-14 19:45:46

我找到了解决这个问题的方法,如果有人需要的话:

代码语言:javascript
复制
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;

它使用一个动态变量,该变量在每一步中都会发生变化。

票数 0
EN

Stack Overflow用户

发布于 2019-08-14 17:01:39

我想你想:

代码语言:javascript
复制
select . . .,
       row_number() over (order by (popularity is not null) desc, popularity desc, id) as newOrder
from t;
票数 0
EN

Stack Overflow用户

发布于 2019-08-14 18:23:02

如果您的MySql版本不允许窗口函数:

代码语言:javascript
复制
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+:

代码语言:javascript
复制
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;

演示

结果:

代码语言:javascript
复制
| id  | popularity | neworder |
| --- | ---------- | -------- |
| 1   | 1          | 4        |
| 2   | 1          | 3        |
| 3   | 2          | 2        |
| 4   | 3          | 1        |
| 5   |            | 5        |
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57499053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档