小编典典

MySQL中每组SQL的前N个问题

sql

请问我在从类似于以下所示的数据集中查询每个类别的前N名时遇到问题。我在此看到了各种线程,但是我在使他们的查询适应于我的特定问题时遇到了问题。

+----+---------------------------------+-------+
| ID | Prod                            |Cat Id |
+----+---------------------------------+-------+
|  1 |  kntrn                          |     1 |
|  2 | kntrn e                         |     1 |
|  3 | e spl                           |     1 |
|  4 | spl php                         |     1 |
|  5 | php cicarredgtal                |     1 |
|  6 | cicarredgtal servecounterstrike |     1 |
|  7 | servecounterstrike com          |     1 |
|  8 |  zlv                            |     2 |
|  9 | zlv enter                       |     2 |
| 10 | spl php                         |     2 |
+----+---------------------------------+-------+

我要基于此规则分组(1)为每个catid选择“前3个产品”。

请注意,从这个意义上讲,top是所有类别中最高的产品数。

因此,对于上面的示例,spl php对于catID 1最高,因为它在所有类别中都出现两次。


阅读 161

收藏
2021-04-15

共1个答案

小编典典

这可能不是很漂亮,但我认为它会起作用:

SELECT cat_id, prod, pos FROM (
    SELECT cat_id, pos, prod, if(@last_id = cat_id, @cnt := @cnt + 1, (@cnt := 0 || @last_id := cat_id)) cnt
    FROM (
        SELECT p.cat_id, pseq.cnt pos, pseq.prod
        FROM (
            SELECT prod, count(*) cnt FROM prods GROUP BY prod ORDER BY cnt DESC
        ) pseq
        INNER JOIN prods p ON p.prod = pseq.prod
        ORDER BY cat_id, pseq.cnt DESC
    ) po
) plist
WHERE cnt <= 3;

Based on the above data, this will return:
+--------+-----------+-----+
| cat_id | prod      | pos |
+--------+-----------+-----+
|      1 | spl php   |   2 |
|      1 |  kntrn    |   1 |
|      1 | kntrn e   |   1 |
|      2 | spl php   |   2 |
|      2 |  zlv      |   1 |
|      2 | zlv enter |   1 |
+--------+-----------+-----+
2021-04-15