Monday, 1 May 2017

mysql - how to get duplicate column values in comma separated




I have a table like this




+----+------------+------------+---------+-----+------+------+
| id | is_deleted | sort_order | version | cid | pid | qid |
+----+------------+------------+---------+-----+------+------+
| 1 | | 1 | 0 | 1 | 1 | 1 |
| 2 | | 2 | 0 | 1 | 1 | 2 |
| 3 | | 3 | 0 | 1 | 1 | 3 |
| 4 | | 1 | 0 | 1 | 2 | 7 |
| 5 | | 2 | 0 | 1 | 2 | 1 |
| 6 | ☺ | 1 | 1 | 1 | 6 | 14 |

| 7 | ☺ | 1 | 1 | 1 | 5 | 13 |
| 8 | | 1 | 0 | 1 | 4 | 12 |
| 9 | | 3 | 0 | 1 | 2 | 2 |
| 10 | | 4 | 0 | 1 | 1 | 4 |
| 11 | | 5 | 0 | 1 | 1 | 5 |
+----+------------+------------+---------+-----+------+------+


as you can see pid is repeated.
Is it possible to get like below format




pid      qid
1 1,2,3,4,5
2 7,1,2
6 14
5 13
4 12


I tried like this but the output I got is




SELECT pid,GROUP_CONCAT(qid) FROM client_parent_question

------+--------------------------+
pid | GROUP_CONCAT(qid) |
------+--------------------------+
1 | 1,2,3,7,1,14,13,12,2,4,5 |
------+--------------------------+

Answer




You are missing group by



SELECT pid,GROUP_CONCAT(qid) FROM client_parent_question group by pid

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...