Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join votes table and sum all votes

Tags:

sql

join

mysql

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:

Quotes

+----+-----------------------------------------------------------------------+
| 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.         |
+----+-----------------------------------------------------------------------+

Votes

+----+-------+------+
| 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?

like image 881
Fabianius Avatar asked Jul 07 '11 13:07

Fabianius


2 Answers

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).

like image 124
Tadeck Avatar answered Nov 12 '22 01:11

Tadeck


SELECT
  ID, quote, (SELECT sum(vote) from votes where votes.quote=quotes.ID)
FROM 
  quotes 
like image 3
CristiC Avatar answered Nov 11 '22 23:11

CristiC