I've got two tables. One of them contains quotes and the other one lists all given votes (either +1 or -1) for each quote. For demonstration purposes I've made simplified versions of the two tables:
+----+-----------------------------------------------------------------------+
| ID | quote |
+----+-----------------------------------------------------------------------+
| 1 | If you stare into the Abyss long enough the Abyss stares back at you. |
| 2 | Don't cry because it's over. Smile because it happened. |
| 3 | Those that fail to learn from history, are doomed to repeat it. |
| 4 | Find a job you love and you'll never work a day in your life. |
+----+-----------------------------------------------------------------------+
+----+-------+------+
| ID | quote | vote |
+----+-------+------+
| 1 | 1 | -1 |
| 2 | 1 | -1 |
| 3 | 3 | 1 |
| 4 | 3 | -1 |
| 5 | 3 | 1 |
| 6 | 3 | -1 |
| 7 | 4 | 1 |
| 8 | 4 | 1 |
| 9 | 4 | 1 |
+----+-------+------+
I'd like to list all quotes on my site and show the respective vote count besides. At first, the SQL query should read all quotes and afterwards join the votes table. However, it should finally list the sum of all votes for each quote. The result of the SQL query will therefore look as follows:
+----+-----------------+------+
| ID | quote | vote |
+----+-----------------+------+
| 1 | If you stare... | -2 |
| 2 | Don't cry... | NULL |
| 3 | Those that... | 0 |
| 4 | Find a job... | 3 |
+----+-----------------+------+
How does the SQL query look like that does the previously described?
SELECT
`quotes`.`id` as `ID`,
`quote`.`quote` as `quote`,
SUM(`votes`.`vote`) AS `vote`
FROM `quotes`
LEFT JOIN `votes`
ON `quotes`.`id` = `votes`.`quote`
GROUP BY `quotes`.`id`
should do the trick.
Assuming id
columns are primary keys (they are unique for each record).
SELECT
ID, quote, (SELECT sum(vote) from votes where votes.quote=quotes.ID)
FROM
quotes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With