gpt4 book ai didi

mysql - 在 MySQL 查询中按记录排序并随机混合

转载 作者:可可西里 更新时间:2023-11-01 08:49:33 25 4
gpt4 key购买 nike

我正在从我对 MySQL 数据库的查询中寻找一种特殊的要求,我想以不同的方式应用 order by。例如。在具有以下数据的 user_iduser_ratinguser_department 字段的数据库中。

+------------------------------------------------------+
| user_id | user_rating | user_department |
+------------------------------------------------------+
| 1 | 102 | A |
| 2 | 33 | B |
| 3 | 43 | C |
| 4 | 54 | A |
| 5 | 63 | A |
| 6 | 214 | B |
| 7 | 82 | A |
| 8 | 87 | C |
| 9 | 43 | A |
| 10 | 98 | A |
| 11 | 73 | C |
| 12 | 31 | A |
+------------------------------------------------------+

鉴于上述结构,我想按照 each_departmentuser_rating 顺序对结果进行排序,我需要每个 user_department 最多 5 条记录,其中初始 3 条记录应该是按照他们的评分顺序,但其余 2 应该是随机的。

所以在上述情况下,输出将类似于:

+------------------------------------------------------+
| user_id | user_rating | user_department |
+------------------------------------------------------+
| 1 | 102 | A |
| 10 | 98 | A |
| 7 | 82 | A |
| 12 | 31 | A |
| 5 | 63 | A |
| 6 | 214 | B |
| 2 | 33 | B |
| 8 | 87 | C |
| 11 | 73 | C |
| 3 | 43 | C |
+------------------------------------------------------+

我尝试了 web 上可用的选项来自定义排序依据,例如使用 FIELD 函数,但在这里找不到那么有用。还尝试使用子查询解决它,但该选项看起来也不可行,因为 MySql 不允许我在查询中同时使用 IN 和 LIMIT 关键字。

有没有更好/更简单的方法来解决这个问题。

最佳答案

这不是您要找的东西,但它提供了一种方法。

想法是使用 group_concat() 将每个部门的前 5 个值放在一个列中。此列的形式为:

user_id:rating

最多重复五次,以逗号分隔。如:

1:182,10:98,7:82,12:31,5:63

执行此操作的查询是:

select user_department,
substring_index(group_concat(concat(user_id, ':', user_rating)
order by user_rating desc
), ',', 5)
from t
group by user_department;

这不处理最后两个值的随机化。它把所有东西都排成一排。但是,我认为这可能会有所帮助。

我的下一次尝试技术上会按照您的要求进行,但它冒着最后两个“随机”用户可能相同的风险。

它使用与上面相同的 group_concat() 技巧。然而,它通过使用 substring_index() 从列表中选择不同的值来超越:

select u.user_id, user_id.user_rating, u.user_department
from (select (case when n.n in (1, 2, 3) or ud.numusers <= 5
then cast(substring_index(substring_index(users, ',', n.n), ',', -1) as unsigned)
else CAST(substring_index(substring_index(users, ',', 4 + rand()*(num_users - 3)), ',', -1) as unsigned)
end) as user_id
from (select user_department,
group_concat(user_id order by user_rating desc) as users,
count(*) as numusers
from t
group by user_department
) ud join
(select 1 as n union all select 2 union all select 3 union all select 4 union all select 5
) n
on n.n <= ud.numusers
) u join
t
on u.user_id = t.user_id
order by user_department, user_rating desc

关于mysql - 在 MySQL 查询中按记录排序并随机混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17660713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com