Soldato
I've become a tad stumped with a little SQL issue.
I have 3 tables, a table of quotes, a table of votes and a table of comments. I need a query that pulls out list of quotes, pulls out the sum and count of votes for each one of those quotes, and the number of comments for each quote. My table structure looks like this:
And my current query is this:
The problem is that while it's pulling out the votes data fine, the number of comments it pulls out is either 0 if there are no comments, or the number of votes if there are any comments at all. For some reason as soon as there's a single comment it uses the number of votes as the count. I know this is something to do with the way I've done the joins, but I can't work out how else I could do it without a lot of extra queries. Unfortunately the DBMS I'm stuck with is MySQL 4.0.24.
I have 3 tables, a table of quotes, a table of votes and a table of comments. I need a query that pulls out list of quotes, pulls out the sum and count of votes for each one of those quotes, and the number of comments for each quote. My table structure looks like this:
Code:
qdb_comments
---------------------------------------------------------------
| id | quoteid | name | website | comment | postdate | ipaddr |
---------------------------------------------------------------
qdb_votes
--------------------------------
| id | quoteid | vote | ipaddr |
--------------------------------
qdb_quotes
-----------------------------------------------------
| id | content | note | email | postdate | approved |
-----------------------------------------------------
Code:
SELECT q.id, q.content, q.note, q.postdate, q.approved, COUNT(v.id) AS votes, CAST(SUM(v.vote) AS SIGNED) AS score, COUNT(c.id) AS comments FROM qdb_quotes q LEFT OUTER JOIN qdb_votes v ON v.quoteid = q.id LEFT OUTER JOIN qdb_comments c ON c.quoteid = q.id WHERE q.approved = 1 GROUP BY q.id ORDER BY q.id DESC LIMIT 0, 10;