Hi,
I have a table with 10,000 names.
I'd like to group them into groups of 3 and also display the remaining 1.
Can anybody help with a suitable query please.
Taffd
and -- two practical ways to make contiguous groups of three (with any leftover shown as the final smaller group): do it in SQL or do it in PHP. Important: grouping depends on row order, so always use an explicit ORDER BY for predictable results.
SQL (MySQL 8+ using window functions)
SELECT ((rn - 1) DIV 3) + 1 AS group_no, *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY <order_col>) AS rn
FROM my_table
) AS t
ORDER BY group_no, rn; SQL (older MySQL using user variables)
SET @rn := 0;
SELECT ((rn - 1) DIV 3) + 1 AS group_no, *
FROM (
SELECT @rn := @rn + 1 AS rn, t.*
FROM my_table t
ORDER BY <order_col>
) AS numbered; Note: initialize the variable separately and number rows inside a subquery so the ORDER BY is applied before numbering. User-variable behavior can be non-deterministic in complex queries, so test results.
PHP (application-level grouping)
$rows = [];
$stmt = $pdo->query('SELECT * FROM my_table ORDER BY <order_col>');
while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) $rows[] = $r;
$groups = array_chunk($rows, 3);
foreach ($groups as $i => $grp) {
echo "Group ".($i+1)."\n";
foreach ($grp as $row) echo $row['your_column']."\n";
} Or stream and chunk on the fly to avoid storing everything in memory: increment a counter, push rows into a temporary array, output and reset when its size hits 3.
Performance notes: for typical sizes the DB solutions are efficient; PHP is simpler to control presentation. Index the column used in ORDER BY for faster sorting.
Jump to Post— phper 9Do you have the column names?
Do you have the column names?
Hi phper,
There is only one column - 'name'.
The table is called 'names'.
Research I've done suggests this cannot be done with sql and will need to be done with php - but I can't work out how to do that either.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.