I have a table like this (shown without any grouping) and am using MySQL 5.5.
mytable
================================================================================
id type parent_type type_id content parent_id
================================================================================
1 type1 NULL 3 john's test content NULL
2 type1 NULL 3 hi there, this is john NULL
3 type2 ptype1 4 john@gmail.com 2
4 type3 ptype1 2 John Smith 2
5 type3 ptype1 8 Sean John John 10
6 type3 ptype1 13 John Smith 11
I would like to group all the rows first by by parent_type and parent_id then type and type_id. Parent_type and parent_id can be some times NULL, but NULLs should not be grouped.
Here’s what I am trying at the moment:
SELECT id, type, IFNULL(parent_type, UUID()) as parent_type, type_id, content, IFNULL(parent_id, UUID()) as parent_id
FROM mytable
WHERE MATCH(content) AGAINST('john*' IN BOOLEAN MODE) GROUP BY parent_type, parent_id, type_index, type_id LIMIT 10 ;
But the desired result is, I want the result to be grouped by parent_type and parent_id first, and then grouped by parent_type and parent_id like so:
mytable
================================================================================
id type parent_type type_id content parent_id
================================================================================
1 type1 NULL 3 john's test content NULL
3 type2 ptype1 4 john@gmail.com 2
5 type3 ptype1 8 Sean John John 10
6 type3 ptype1 13 John Smith 11
How can this be done?
Using a subquery did the trick: