加入投票表并总结所有投票

时间:2011-07-07 13:39:04

标签: mysql sql join

我有两张桌子。其中一个包含引号,另一个列出每个引用的所有给定投票(+1或-1)。出于演示目的,我已经制作了两个表的简化版本:

行情

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

我想在我的网站上列出所有报价并显示相应的投票数。首先,SQL查询应读取所有引号,然后加入投票表。但是,它应该最终列出每个报价的所有投票的总和。因此,SQL查询的结果如下所示:

+----+-----------------+------+
| ID | quote           | vote |
+----+-----------------+------+
|  1 | If you stare... |   -2 |
|  2 | Don't cry...    | NULL |
|  3 | Those that...   |    0 |
|  4 | Find a job...   |    3 |
+----+-----------------+------+

SQL查询与前面描述的一样?

6 个答案:

答案 0 :(得分:6)

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`

应该这样做。

假设id列是主键(它们对每条记录都是唯一的)。

答案 1 :(得分:2)

SELECT
  ID, quote, (SELECT sum(vote) from votes where votes.quote=quotes.ID)
FROM 
  quotes 

答案 2 :(得分:0)

SELECT q.id, q.quote, SUM(v.vote ) as summ
FROM Quotes q 
LEFT JOIN Votes v ON q.id=v.quote 
GROUP BY q.id, q.quote                                                                 ;

答案 3 :(得分:0)

以下内容应该有效。左连接表示即使没有行也包括投票摘要。

select ID, quote, total_votes from quotes
left join 
(select quote, sum(vote) as total_votes from quotes
 group by quote) ) as vote_totals
on quotes.ID = vote_totals.quote

答案 4 :(得分:0)

Select q.id, q.quote, sum(v.vote) from
quotes q
inner join votes v on
q.id= v.quote
group by v.quote

答案 5 :(得分:0)

SELECT Quotes.ID ID, Quotes.QUOTE QUOTE, SUM(Votes.vote) VOTE FROM Quotes LEFT JOIN Votes ON Votes.quote = Quotes.id