MySQL Complex Join优化

时间:2012-04-25 05:42:10

标签: mysql

我有一个结果集,我从三个表之间的连接中使用:

获得
SELECT X.*, Y.Name FROM `A` AS X
INNER JOIN `B` AS Y
INNER JOIN `C` AS Z
ON X.id=Y.id AND X.categoryID=Z.categoryID
WHERE X.userID_FK=%d AND X.listID_FK=%d 
ORDER BY Z.categoryRank ASC

我有第四个表'D',其中包含:

-------------------------------
  id_FK    userID_FK    vote
-------------------------------

这里(id_FK, userID_FK)对是PK。

第一个查询返回的每个X.id可能在D表中有多个条目。通常,对于每个返回的行,为了计算每id的投票数,我会写一个类似的查询:

SELECT SUM(vote) FROM D WHERE `id`=%d

我想知道我是否可以将这两个查询优化为单个查询,因为当前方案会导致O(n)执行时间。 n是第一个查询返回的结果数。

1 个答案:

答案 0 :(得分:3)

你可以像这样做

SELECT
X.*,
Y.Name,
(SELECT
   SUM(vote)
   FROM D
   WHERE `id` = X.id) as Count
FROM `A` AS X
INNER JOIN `B` AS Y
INNER JOIN `C` AS Z
ON X.id = Y.id
  AND X.categoryID = Z.categoryID
WHERE X.userID_FK =  % d
AND X.listID_FK =  % d
ORDER BY Z.categoryRank ASC