Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql GROUP_CONCAT of first n rows

Tags:

mysql

Is it possible to get comma separated value of first n (say 10 rows of a column) rows using Mysql?

I have a query to get data greater than CURDATE(). And it will return more than 100 rows of result. What I want is, GROUP_CONCAT the first 10 rows of result.

This is my query:

SELECT GROUP_CONCAT(user_id) AS userids
FROM user_tasks
WHERE due_date > CURDATE() LIMIT 10;

am getting entire rows. I need first 10 rows only

Thanks

like image 805
V-T Avatar asked Jan 09 '14 13:01

V-T


2 Answers

Use subquery:

SELECT 
  GROUP_CONCAT(user_id) AS userids
FROM
  (SELECT 
    user_id
  FROM
    user_tasks
  WHERE due_date > CURDATE()
  LIMIT 10) AS users
like image 146
Alma Do Avatar answered Sep 25 '22 14:09

Alma Do


You need to use a sub query to impose the limit, like this:

SELECT GROUP_CONCAT(sub_query.user_id) AS userids
FROM 
(
  SELECT user_id
  FROM user_tasks
  WHERE due_date > CURDATE() 
  LIMIT 10
) sub_query
like image 37
Ike Walker Avatar answered Sep 21 '22 14:09

Ike Walker