1

我有一个这样的表(显示没有任何分组)并且正在使用 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

我想先按 by 然后对所有parent_type行进行parent_id分组。并且可以是一些次,但不应该分组。typetype_idParent_typeparent_idNULLNULLs

这是我目前正在尝试的:

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_typeandparent_id分组,然后按parent_typeand分组,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

如何才能做到这一点?

4

1 回答 1

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 ;
于 2012-04-20T06:56:38.487 回答