2016-10-12 85 views
1

我有以下表格: fpt_action_handling(含10.000.000記錄替代自聯接包含MAX()和GROUP BY提高性能

id  | name |   action_id  | action_definition | sortorder | 
------ | ------ |  -----------  | ------   | ------ | 
UUID() | name | id of table "actions" | UUID()   | INT(11) | 

ID,的action_id,排序順序有一個索引3GB大

每個的action_id我想最高的排序順序(排名)的action_definition

我寫了下面的查詢:

select fa.id, fa.action_id 
from fpt_action_handling fa 
inner join (select action_id, max(sortorder) max_sortorder from ftp_action_handling group by action_id) ma 
on fa.action_id = ma.action_id 
and fa.sortorder = ma.max_sortorder 

查詢需要5分鐘才能完成,並且會在服務器上產生巨大的負載。

我怎樣才能擺脫max()和GROUP BY,而不會失去獲取action_id的要求,其中每個action_id具有最高的排序順序? (如柱的action_id不是唯一

回答

0

嘗試外連接:

SELECT a.id, a.action_id 
FROM fpt_action_handling a 
LEFT JOIN fpt_action_handling b 
    ON b.action_id = a.action_id 
    AND b.sortorder > a.sortorder 
WHERE b.action_id IS NULL