小编典典

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

sql

我有两张桌子。其中一个包含引号,另一个列出每个引号的所有给定票数(+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查询的外观如前所述吗?


阅读 216

收藏
2021-04-22

共1个答案

小编典典

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列是主键(它们对于每个记录都是唯一的)。

2021-04-22