I have two tables, one for articles/polls, and one for the votes on these articles. Votes are held in an enum field for up/down, and a couple other options. I am trying to create a query that will bring back the data I need for the article, and also give me the sum of all the votes. Unfortunately, I am getting an unexpected result. It is tallying all my votes as though they were cast for the first entry, and none for any others.
How can I properly link my votes to the polls they belong with?
tblVotes
[PK] primaryId | voterId (FK) | voteValue (enum) | postID (fk)
----------------------------------------------------------------------
1 10 up 1
2 11 down 1
3 11 up 10
tblContent
[PK] unique Id | postTitle | postBody | postAuthor(FK) |
------------------------------------------------------------------
1 foo foofoo 12
10 bar barbar 10
11 foobar foofoobarbar 10
When I tun the query detailed below, I expect I would get results like this:
uniqueId |userName | pollDate | postTitle |postBody | upVotes| downVotes
--------------------------------------------------------------------------
1 bob 1/1/11 foo foofoo 1 1
10 john 1/2/11 bar barbar 1 null
11 john 1/3/11 foofoo foofoobar.. null null
Unforunately, I am actually getting results like this:
uniqueId |userName | pollDate | postTitle |postBody | upVotes| downVotes
--------------------------------------------------------------------------
1 bob 1/1/11 foo foofoo 2 1
10 john 1/2/11 bar barbar null null
11 john 1/3/11 foofoo foofoobar.. null null
Here is my SQL statement:
SELECT
tblContent.uniqueID,
tblUsers.userName,
tblContent.postDate,
tblContent.postTitle,
tblContent.postBody,
votes.upVotes,
votes.downVotes
FROM
tblContent
LEFT JOIN
(
SELECT
postId,
SUM(CASE WHEN tblVotes.voteType = 'up' THEN 1 ELSE 0 END) as upVotes,
SUM(CASE WHEN tblVotes.voteType = 'down' THEN 1 ELSE 0 END) as downVotes
FROM
tblVotes, tblContent
WHERE
tblContent.uniqueId = tblVotes.postId
) votes
ON tblContent.uniqueId = votes.postId
LEFT JOIN
tblUsers
ON tblUsers.userId = tblContent.postAuthor
WHERE
postApproved = true
ORDER BY
postDate DESC
Needed to
GROUP BYin the nested SQL statement.