Concatenating multiple rows of a result set
15/02/2009This is needed when you need to concatenate multiple rows of a result set in MySQL.
CREATE TABLE services (
id INT UNSIGNED NOT NULL,
client_id INT UNSIGNED NOT NULL,
KEY (id)
);
INSERT INTO services
VALUES (1,1),(1,2),(3,5),(3,6),(3,7);
SELECT id,client_id
FROM services
WHERE id = 3;
+----+-----------+
| id | client_id
+----+-----------+
| 3 | 5
| 3 | 6
| 3 | 7
+----+-----------+
SELECT id,GROUP_CONCAT(client_id)
FROM services
WHERE id = 3 GROUP BY id;
+----+-------------------------+
| id | GROUP_CONCAT(client_id)
+----+-------------------------+
| 3 | 5,6,7
+----+-------------------------+
The group_concat function is affected by the group_concat_max_len and the max_allowed_packet variables. So, if you need to concatenate more than mysql can handle by default(1024 bytes) you just change the max_allowed_packet in my.cnf and set this:
SET [SESSION | GLOBAL] group_concat_max_len = VALUE;
into your session.
No comments yet.