【问题标题】:Alternative to a self join containing max() and GROUP BY to improve performance替代包含 max() 和 GROUP BY 的自联接以提高性能
【发布时间】:2016-10-12 14:42:23
【问题描述】:

我有下表: fpt_action_handling(3GB 大,包含 10.000.000 条记录

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

id, action_id, sortorder 有索引

在每个 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 列不是唯一的

【问题讨论】:

    标签: mysql join max self rank


    【解决方案1】:

    尝试外部连接:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 2018-02-14
      • 2010-11-20
      相关资源
      最近更新 更多