gpt4 book ai didi

mysql - 每组前 N 行仅获得 1 行

转载 作者:行者123 更新时间:2023-11-29 10:56:18 24 4
gpt4 key购买 nike

我试图显示每个类别的前 3 个(或任意数量)住房。顶部意味着访问量最大。所以如果我有一个像这样的表:

+------------+--------------------+--------+
| housing_id | category | visits |
+------------+--------------------+--------+
| 7 | cat | 2 |
| 8 | New Category | 1 |
| 10 | bead and breakfast | 1 |
| 11 | bead and breakfast | 4 |
| 15 | 2 | 3 |
| 16 | 2 | 1 |
| 17 | New Category | 1 |
| 18 | cat | 1 |
+------------+--------------------+--------+

我和我想选择每个类别中访问量最大的前 3 个住房,所以我这样做了。

select housing_id, category, visits
from
(select housing_id, category, visits,
@category_rank := if(@current_category = category, @country_rank + 1, 1) as category_rank,
@current_category := category
from visit_counts
order by category, visits desc
) ranked
where category_rank <= 3;

我得到:

+------------+--------------------+--------+
| housing_id | category | visits |
+------------+--------------------+--------+
| 15 | 2 | 3 |
| 11 | bead and breakfast | 4 |
| 7 | cat | 2 |
| 8 | New Category | 1 |
+------------+--------------------+--------+

但我想要:

+------------+--------------------+--------+
| housing_id | category | visits |
+------------+--------------------+--------+
| 15 | 2 | 3 |
| 16 | 2 | 1 |
| 11 | bead and breakfast | 4 |
| 10 | bead and breakfast | 1 |
| 7 | cat | 2 |
| 18 | cat | 1 |
| 8 | New Category | 1 |
| 17 | New Category | 1 |
+------------+--------------------+--------+

最佳答案

您正在使用用户变量但未声明它们。另外,您应该在一个表达式中分配和读取用户变量,因为 MySQL 不保证列计算的顺序(因此分配可能发生在您读取它之前或之后)。

试试这个:

select housing_id, category, visits
from (
select housing_id, category, visits,
@category_rank := if(@current_category = category,
@category_rank + 1,
if(@current_category := category, 1, 1)
) as category_rank
from visit_counts, (select @category_rank := 0, @current_category := null) t2
order by category, visits desc
) ranked
where category_rank <= 3;

Demo

关于mysql - 每组前 N 行仅获得 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42967513/

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