I have a table similar to:
ID | NAME | GROUP_ID
1 | rand_str | 4
2 | rand_str | 2
3 | rand_str | 3
4 | rand_str | 0
5 | rand_str | 3
6 | rand_str | 1
7 | rand_str | 3
8 | rand_str | 3
9 | rand_str | 1
10 | rand_str | 0
ID is unique ID, name valie is not null and contains varchar value and group_id is a max 2 digit positive number.
Let’s say that the query returns this table.
What I want is, using PHP, show the results grouped by their group_id and if possible, ordering the group id by the most numbered to least numbered and “0” being always the last no matter how populated it is.
so end result:
group id 3 exists 3 times, so
- 1- id_3, id_5, id_7 and id_8 (group_id 3)
- 2- id_6, id_9 (group_id 1)
- 3- either group id 4 or 2 since both contain 1 item each
- 4- group_id 0, even though it has 2 items -> id_4, id_10
How can I achieve this?
Thank you.
Use a subquery to determine the count of each group (and therefore its order), then join that with your data to retrieve the records:
See it on sqlfiddle.
You would then loop over the results in PHP, keeping track of the
GROUP_IDof the last record and comparing with the current one to see whether you’re now in a new group: