I think I found a solution:
SELECT a.group_id, a.index, (CASE WHEN a.group_id IS NOT NULL THEN a.group_index_min ELSE a.index END) group_index_min FROM ( SELECT p.group_id, p.index, (CASE WHEN @group <> IFNULL(p.group_id, 0) THEN @n := p.index ELSE @n := @n END) group_index_min, @group := IFNULL(p.group_id, 0) FROM temp p ORDER BY p.group_id, p.index ) A ORDER BY (CASE WHEN a.group_id IS NOT NULL THEN a.group_index_min ELSE a.index END)
This works for my example, sorting values by their index (if they do not belong to the group) or by the index of the group (if they belong to the group). Now try applying to my real tables / data :)
If someone wants to see this and say if it contains some of MySQL DONT, I would appreciate it. As I said, I'm not a MySQL expert, so I'm not sure if this is the best way to solve this problem.
source share