如何计算其他表上的连接数

时间:2015-12-04 11:14:44

标签: mysql

如何根据其他人sum

计算

我有这张桌子

CARDS

|   ID  |   Name    |
---------------------
|   1   |   Nice    |
|   2   |   Wow     |
|   3   |   Lol     |
|   4   |   Ohyeah  |
|   5   |   Olala   |

VOTES

ID  |   *card_id*   |   *user_id*   |   vote    |
-------------------------------------------------
1   |       1       |       1       |   -1      |
2   |       2       |       2       |   -1      |
3   |       2       |       4       |   1       |
4   |       2       |       5       |   1       |
5   |       3       |       2       |   1       |
6   |       3       |       1       |   1       |

结果我想要什么

|   card_id     |   total_votes |
-------------------------------
|   1           |   -1      |
|   2           |   1       |
|   3           |   2       |
|   4           |   0       |
|   5           |   0       |

这就是我试过的

SELECT c.*, COALESCE(SUM(v.vote),0) as vote_count 
FROM cards c 
LEFT JOIN votes v ON c.id = v.card_id

我不在哪里,我需要帮助

3 个答案:

答案 0 :(得分:0)

您应该选择所有投票并按card_id对它们进行分组。你可以简单地使用SUM函数。

SELECT c.id, COALESCE(SUM(v.vote), 0) 
FROM VOTES 
LEFT JOIN c ON v.card_id = c.ID 
GROUP BY v.card_id

答案 1 :(得分:0)

你不需要子查询,只需要

<强> SQL Fiddle Demo

SELECT c.`ID`, 
       COALESCE(Sum(v.vote), 0) AS total_votes 
FROM   cards c 
       LEFT JOIN votes v 
              ON c.id = v.`card_id`
GROUP  BY c.`ID`;

<强>输出

| ID | total_votes |
|----|-------------|
|  1 |          -1 |
|  2 |           1 |
|  3 |           2 |
|  4 |           0 |
|  5 |           0 |

答案 2 :(得分:0)

以下查询可以解决问题

select c.id, sum(v.vote)
from cards c, votes v
where c.id = v.card_id
group by c.id