GROUP_CONCAT useful GROUP BY extension

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:
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 |
+----+-------------------------+
Handling in PHP:
old way:
query("SELECT id,client_id FROM services WHERE id = 3");
while ($row = $res->fetch_array(MYSQLI_ASSOC)) {
$result[] = $row['client_id'];
}
$res->free();
?>
with group_concat:
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();
?>
This should work faster, as we remove loop from PHP to MySQL server side.
Also it can be handy to use result concatenated string as part of IN statement:
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

?>
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.
One more thing: you may want to add ORDER BY NULL statement after GROUP_BY to avoid
unnecessary sorting with filesort
Farhamdani

Sharing insights on tech, blogging, and passive income. Follow for more at farhamdani.eu.org!

Drop your comments, but make sure they’re related to the discussion!

I'd be grateful if you could read the Commenting Rules on this blog before posting a comment.

Post a Comment (0)
Previous Post Next Post