增加mysql和GROUP_CONCAT中的计数器

时间:2017-03-24 03:40:58

标签: mysql

这是我的mysql查询:

SELECT users.id, user.name, category.id,
       GROUP_CONCAT(category.name) AS catName,
       @rownum := @rownum + 1 AS row_number
FROM users
JOIN usecat ON id_users=users.id
JOIN category ON id_category=category.id
CROSS JOIN (select @rownum := 0) r
GROUP BY users.id

结果:AAA-1,BBB-3,CCC-8,......

我想得到这样的结果:AAA-1,BBB-2,CCC-3,......

你能帮我改变一下这个问题吗?感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

SET @rownum=1;
SELECT *, @rownum := @rownum + 1 AS row_number 
FROM (SELECT users.id, user.name, category.id,
       GROUP_CONCAT(category.name) AS catName
  FROM users
  JOIN usecat ON id_users=users.id
  JOIN category ON id_category=category.id
GROUP BY users.id) t;