I have a result set that I obtain from the join between three tables using:
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
I have a fourth table ‘D’ which contains:
-------------------------------
id_FK userID_FK vote
-------------------------------
Here (id_FK, userID_FK) pair is a PK.
Each X.id returned by the first query could have multiple entries in the D table. Normally, for each returned row, in order to count votes per id, I’d write a query like:
SELECT SUM(vote) FROM D WHERE `id`=%d
I am wondering if I could optimize these two queries into a single query as the current scheme results in O(n) execution time. n being the number of results returned by the first query.
You can simply do it like this