MySQL分组分阶段

时间:2012-04-20 06:03:58

标签: mysql sql group-by

我有一个这样的表(没有任何分组显示)并使用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_typeparent_id然后typetype_id对所有行进行分组。 Parent_typeparent_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_typeparent_id对结果进行分组,然后按parent_typeparent_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

如何做到这一点?

1 个答案:

答案 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 ;