我试图在一段时间内优化这个。这是一个巨大查询的一个小提取,但这是查询最后变慢的。我认为你可以从中获得简单的表格结构。 有人知道如何做到这一优雅和苗条?
SELECT gref.gid AS gid, COUNT(o.id) AS cnt
FROM objects AS o
RIGHT JOIN group_xref AS gx ON o.id = gx.oid
LEFT JOIN group_xref AS gref ON o.id = gref.oid
LEFT JOIN groups AS groups ON gref.gid = groups.id
WHERE groups.att = 1
GROUP BY gref.gid
好的,这是EXPLAIN: http://htmlpaste.com/ff849935d884a36076f74bd934b0212bac7658e9
答案 0 :(得分:1)
如果不了解表结构和关系,很难说出查询在做什么。我想知道以下查询是否产生了相同的结果以及它是否运行得更快:
select gref.gid AS gid, COUNT(*)
from group_xref gref LEFT JOIN
groups
ON gref.gid = groups.id
WHERE groups.att = 1
GROUP BY gref.gid;
至少,我认为双重加入group_xref
是不必要的。以下是您的查询:
SELECT gx.gid AS gid, COUNT(o.id) AS cnt
FROM group_xref gx left join
objects 0
ON o.id = gx.oid LEFT JOIN
groups groups
ON gx.gid = groups.id
WHERE groups.att = 1
GROUP BY gx.gid;
如果我假设与对象的链接是1-many且所有对象id都有效,那么这简化为:
SELECT gx.gid AS gid, COUNT(gx.id) AS cnt
FROM group_xref gx left join
groups groups
ON gx.gid = groups.id
WHERE groups.att = 1
GROUP BY gx.gid;
(我注意到的是我开始的地方)。
答案 1 :(得分:0)
确保存在以下索引:
objects.id
group_xref.oid
group_xref.gid
groups.id
groups.att
此外,与group_xref的右连接似乎是多余的,请尝试:
SELECT gref.gid AS gid, COUNT(o.id) AS cnt
FROM objects AS o
LEFT JOIN group_xref AS gref ON o.id = gref.oid
LEFT JOIN groups AS groups ON gref.gid = groups.id
WHERE groups.att = 1
GROUP BY gref.gid