如何从MYSQL中的组中查找前N个记录的查询结果
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何从MYSQL中的组中查找前N个记录的查询结果相关的知识,希望对你有一定的参考价值。
我有以下查询,它以desc顺序给出按用户ID分组的名称计数。到目前为止我已经达到了,但不能超越它。我想连接每个用户的前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 |
+---------+----------------+
答案
Ue Kua zxsw Poi:
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
的表达式是单个表达式。 mysql不保证@grp
中表达式的评估顺序,因此单个表达式是安全分配这两个变量的唯一方法。- 变量已初始化。
SELECT
条款是确定“前2”的地方。
以上是关于如何从MYSQL中的组中查找前N个记录的查询结果的主要内容,如果未能解决你的问题,请参考以下文章