GROUP_CONCAT useful GROUP BY extension
MySQL has useful extention to the GROUP BY operation: function GROUP_CONCAT:
GROUP_CONCAT(expr) – This function returns a string result with the concatenated non-NULL values from a group.
Where it can be useful?
For example to get PHP array without looping inside PHP:
Table:
old way:
Also it can be handy to use result concatenated string as part of IN statement:
One more thing: you may want to add ORDER BY NULL statement after GROUP_BY to avoid
unnecessary sorting with filesort
GROUP_CONCAT(expr) – This function returns a string result with the concatenated non-NULL values from a group.
Where it can be useful?
For example to get PHP array without looping inside PHP:
Table:
Handling in PHP: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 |
+----+-------------------------+
old way:
with group_concat:query("SELECT id,client_id FROM services WHERE id = 3");
while ($row = $res->fetch_array(MYSQLI_ASSOC)) {
$result[] = $row['client_id'];
}
$res->free();
?>
This should work faster, as we remove loop from PHP to MySQL server side.query("SELECT id,GROUP_CONCAT(client_id) as clients FROM services WHERE id = 3 GROUP BY id");
$row = $res->fetch_array(MYSQLI_ASSOC);
$result = explode(',', $row['clients']); // $row['clients'] contains string 5,6,7
$res->free();
?>
Also it can be handy to use result concatenated string as part of IN statement:
Sure, last example can be handled with one query with joins, but sometimes we need the temporary ids in clients code, for example to execute query on another server.query("SELECT id,GROUP_CONCAT(client_id) as clients FROM services WHERE id = 3 GROUP BY id");
$row = $res->fetch_array(MYSQLI_ASSOC);
$result = $row['clients']; // $row['clients'] contains string 5,6,7
$res->free();
$resclients=$mysqli->query("SELECT id,client_name FROM clients WHERE id = IN ($result)");
// handle $resclients
?>
One more thing: you may want to add ORDER BY NULL statement after GROUP_BY to avoid
unnecessary sorting with filesort