2012-04-20 72 views
1

我有一個這樣的表(顯示沒有任何分組),並且正在使用MySQL 5.5。MySQL groupby分階段

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   [email protected]    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_idParent_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   [email protected]    2 
5  type3 ptype1   8   Sean John John    10 
6  type3 ptype1   13   John Smith     11 

這怎麼辦?

+1

行3和4不具有相同的type_ids。 – liquorvicar 2012-04-20 06:06:41

+0

啊,我明白了。有沒有辦法通過parent_type和parent_id先分組,然後按類型和type_id對結果進行分組? – F21 2012-04-20 06:08:05

+0

@Jason_vorhees:我寧願在一個查詢中完成所有操作,而不是選擇一個臨時表,然後從中選擇。 – F21 2012-04-20 06:15:11

回答

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 ;