如何在mysql中concat一个组的前n条记录的查询结果

oknwwptz  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(454)

我有下面的查询,它给出按用户id按desc顺序分组的名称计数。我已经达到了目前的程度,但不能超越这一点。我想在每个用户的前2个记录的名称列。
目前的查询是:

SELECT t.*, 
       IF(@grp = t.user_id, @rowno := @rowno + 1, @rowno := 1) AS rowno, 
       @grp := t.user_id AS u_id 
FROM   (SELECT notes.user_id, 
               t.name        name, 
               Count(t.name) ct 
        FROM   notes 
               INNER JOIN tags t 
                       ON notes.id = t.note_id 
        GROUP  BY notes.user_id, 
                  t.name 
        ORDER  BY notes.user_id, 
                  Count(t.name) DESC) t;

结果如下:

+---------+------------+----+-------+-----+
| user_id | name       | ct | rowno | uid |
+---------+------------+----+-------+-----+
| 282     | realifex   | 1  | 1     | 282 |
+---------+------------+----+-------+-----+
| 282     | clear      | 1  | 2     | 282 |
+---------+------------+----+-------+-----+
| 282     | thinking   | 1  | 3     | 282 |
+---------+------------+----+-------+-----+
| 282     | refreshing | 1  | 4     | 282 |
+---------+------------+----+-------+-----+
| 285     | solid      | 2  | 1     | 285 |
+---------+------------+----+-------+-----+
| 285     | clear      | 1  | 2     | 285 |
+---------+------------+----+-------+-----+
| 285     | thinking   | 1  | 3     | 285 |
+---------+------------+----+-------+-----+
| 287     | holidays   | 3  | 1     | 287 |
+---------+------------+----+-------+-----+
| 287     | Larry      | 3  | 2     | 287 |
+---------+------------+----+-------+-----+
| 287     | travel     | 2  | 3     | 287 |
+---------+------------+----+-------+-----+
| 287     | thinking   | 1  | 4     | 287 |
+---------+------------+----+-------+-----+

我尝试将每个用户组的前2个结果合并为一列,如下所示:

+---------+----------------+
| user_id | name           |
+---------+----------------+
| 282     | realifex,clear |
+---------+----------------+
| 285     | solid,   clear |
+---------+----------------+
| 287     | Larry,travel   |
+---------+----------------+
qqrboqgw

qqrboqgw1#

ue公司 group_concat() :

SELECT group_id, group_concat(name order by rn) as names
FROM (SELECT t.*, 
             (@rn := IF(@grp = t.user_id, @rowno := @rowno + 1, 
                        IF(@grp := t.user_id, 1, 1)
                       )
             )  as rn
      FROM (SELECT n.user_id, t.name, n.name,  Count(t.name) ct 
            FROM notes n INNER JOIN
                 tags t 
                 ON notes.id = t.note_id 
            GROUP BY n.user_id,  t.name 
            ORDER BY n.user_id, Count(t.name) DESC
           ) t CROSS JOIN
           (SELECT @rn := 0, @grp := -1) params
     ) t
WHERE rn <= 2
GROUP BY user_id;

注:
的表达式 @rn 以及 @grp 是一个表达式。mysql不保证表达式在 SELECT ,因此只有一个表达式才能安全地分配这两个变量。
变量已初始化。
这个 WHERE 子句是确定“前2名”的地方。

相关问题