Skip to content
Advertisement

How to select all enteties grouped by common propertie without loop?

Is there any way to fatch all entities from table grouped by common property while loop?

Table storage looks like this

id         |  product_id   | category_id
-----------+-----------------------+--------------------------
1          |       1       | 15
2          |       2       | 17
3          |       3       | 18
4          |       4       | 17
5          |       5       | 15
6          |       6       | 17
7          |       7       | 18

and final result supposed to look like this

    id         |  product_id   | category_id
    -----------+-----------------------+--------------------------
    1          |       1       | 15
    2          |       2       | 17
    3          |       3       | 18
    4          |       5       | 15
    5          |       4       | 17
    6          |       7       | 18
    7          |       6       | 15

What i want is this:

Select each record grouped by category id. It means, if table size is 3200, i need to select all of 3200 records grouped by category id in ASC order

Advertisement

Answer

You seem to want the values interleaved. You can use row_number() in the order by:

select s.*
from storage s
order by row_number() over (partition by storage_id order by id),
         storage_id;

Here is a db<>fiddle.

EDIT:

In older versions of MySQL, you can assign a sequential number within each group using variables and then use that for ordering:

select s.*
from (select s.*,
             (@rn := if(@sid = storage_id, @rn + 1,
                        if(@sid := storage_id, 1, 1)
                       )
             ) as seqnum
      from (select s.* from storage s order by storage_id, id) s cross join
           (select @rn := 0, @sid := -1) params
     ) s
order by seqnum, id;

The SQL Fiddle has both methods.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement