我有下面的查询,它给出按用户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 |
+---------+----------------+
1条答案
按热度按时间qqrboqgw1#
ue公司
group_concat()
:注:
的表达式
@rn
以及@grp
是一个表达式。mysql不保证表达式在SELECT
,因此只有一个表达式才能安全地分配这两个变量。变量已初始化。
这个
WHERE
子句是确定“前2名”的地方。