我有一个这样的表(显示时没有任何分组)并且我使用的是 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
如何做到这一点?
最佳答案
使用子查询就可以了:
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 ;
关于MySQL 分阶段分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10241075/