1

我有一个结果集,我使用以下方法从三个表之间的连接中获得:

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)的pair是PK。

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

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

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

4

1 回答 1

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
于 2012-04-25T06:33:52.860 回答