I have a table I want to get a sum of information on, but the value I need to query on is in two different tables.
The one with values I need to sum is say, kudos, which has a value indicating +1 (1) or -1 (2) in the Action column, which is associated to the discussion it's on, or the comment it's on:
Kudos +-----------+--------------+--------+ | CommentID | DiscussionID | Action | +-----------+--------------+--------+ | 24 | NULL | 1 | | NULL | 4 | 1 | | 60 | NULL | 2 | +-----------+--------------+--------+
The value I want to filter by is the author's ID, which is either in the Comment table or the Discussion table:
Comments +-----------+--------+ | CommentID | Author | +-----------+--------+ | 29 | 5 | | 24 | 1 | | 22 | 1 | | 21 | 1 | +-----------+--------+ Discussions +--------------+--------+ | DiscussionID | Author | +--------------+--------+ | 4 | 1 | | 5 | 2 | | 6 | 2 | | 7 | 7 | +--------------+--------+
In this example, Author 1 would have a score of 2, because row 1 in the Kudos table would count because it matches with row 1 in the comment table, and row 2 in the Kudos table matches the 1st row in the Discussions table.
Additionally, I need to use the query that does this as a subquery, because I'm getting all the users in a select statement, and then getting the sum of this subquery as a field associated with the userID, like:
SELECT tblUser.Name AS Name, (subquery) AS rep FROM User_Table AS tblUser;
What I've come up with is the following:
SELECT tblU.Name AS Name, tblU.UserID AS ID,
(SELECT SUM(IF(Action=1, 1, -1)) FROM Kudos AS tblK
LEFT JOIN Discussions AS tblD ON tblK.DiscussionID = tblD.DiscussionID
LEFT JOIN Comments AS tblC ON tblC.CommentID = tblK.CommentID
WHERE tblD.InsertUserID = id OR tblC.InsertUserID = id) AS rep
FROM Users AS tblU;
which gives me:
+--------------+----+------+ | Name | id | rep | +--------------+----+------+ | Jack | 1 | 357 | | Joe | 2 | 824 | | Jim | 12 | 48 |
But it takes 0.23 seconds to run for a small set (like 13 users). I've heard from co-workers that the OR condition is bad for performance, but I'm not sure how this can be optimized at all.