我有一个这样的表(没有任何分组显示)并使用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
我想先按parent_type
和parent_id
然后type
和type_id
对所有行进行分组。 Parent_type
和parent_id
可能有时NULL
,但不应将NULLs
分组。
这就是我现在正在尝试的内容:
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 ;
但理想的结果是,我希望首先按parent_type
和parent_id
对结果进行分组,然后按parent_type
和parent_id
进行分组,如下所示:
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
如何做到这一点?
答案 0 :(得分:0)
使用子查询可以解决问题:
SELECT *
FROM (
SELECT id, type, type_id, content, MATCH(content) AGAINST('john') as relevance, IFNULL(parent_type, UUID()) as parent_type, IFNULL(parent_id, UUID()) as parent_id
FROM mytable WHERE MATCH(content) AGAINST('john*' IN BOOLEAN MODE) GROUP BY parent_type, parent_id
) as search
GROUP BY search.type, search.type_id DESC LIMIT 10 ;