0

我试图优化这个有一段时间了。这是一个巨大查询的一小部分,但这就是查询最终变慢的原因。我认为您可以从中获得简单的表结构。有人知道如何做到这一点优雅和苗条吗?

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

好的,这里是解释:http: //htmlpaste.com/ff849935d884a36076f74bd934b0212bac7658e9

4

2 回答 2

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;

(我注意到这是我开始的地方)。

于 2013-05-23T13:33:33.803 回答
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
于 2013-05-23T13:06:06.947 回答