如果有两个帖子表,如何计算总票数?

时间:2015-11-18 15:15:34

标签: mysql join union-all

以下是我的表格的结构

// table1
+----+-------+--------------------+
| id | color |      content       |
+----+-------+--------------------+
| 1  | blue  | it is a bad color  |
| 2  | red   | it is a good color |
| 3  | green | I don't like this  |
+----+-------+--------------------+

// table2
+----+-------+---------------------+
| id | site  |     description     |
+----+-------+---------------------+
| 1  | stack | help to programmers |
| 2  | google| everything you like |
+----+-------+---------------------+

// votes
+----+-----------+---------+-------+
| id | table_code| post_id | value |
+----+-----------+---------+-------+
| 1  |  1        | 1       |  1    |  // table1, post1, +1upvote     (blue)
| 2  |  1        | 2       | -1    |  // table1, post2, -1downvote   (red)
| 3  |  2        | 1       |  1    |  // table2, post1, +1upvote     (stack)
+----+-----------+---------+-------+

此处还有查询

select t3.*, (select sum(value) from votes v where t3.id = v.post_id) total_votes
   from (
      select * from table1
        union all
      select * from table2
   ) t3

这是我的输出

+----+-------+---------------------+-------------+
| id | color |       content       | total_votes |
+----+-------+---------------------+-------------+
| 1  | blue  | it is a bad color   |  2          |  // Problem (it should be 1)
| 2  | red   | it is a good color  | -1          |
| 3  | green | I don't like this   |  0          |
| 1  | stack | help to programmers |  2          |  // Problem (it should be 1)
| 2  | google| everything you like |  0          |
+----+-------+---------------------+-------------+

正如您在此^表中看到的,total_votes的计算错误。我该如何解决?

注意:根据实际情况,我无法合并table1table2。所以,请不要告诉我你的结构是疯了。

1 个答案:

答案 0 :(得分:1)

您还必须在table_code中指定UNION

select t3.*, 
       (select sum(value) 
        from votes v 
        where t3.id = v.post_id and 
              v.table_code = t3.table_code) total_votes
   from (
      select *, 1 table_code from table1
        union all
      select *, 2 from table2
   ) t3

在相关子查询中使用table_code,我们可以从votes表中选择正确的值。