mysql - 有两个Posts表时如何计算总票数?

标签 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。所以,请不要告诉我你的结构很疯狂。

最佳答案

您还必须在 UNION 中指定 table_code:

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 表中选择正确的值。

关于mysql - 有两个Posts表时如何计算总票数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33783718/

相关文章:

mysql - MySql中如何使用触发器制作外键

sql - 基于一列对数据进行分组

sql-server - 为什么join子句的顺序会影响SQL Server中的查询计划?

sql - 如何联合 SELECT 两个具有两个表的 ID 的表?

sql - 对所有结果进行分组 SQL Server

mysql - 索引的速度是否大于 MySQL 中的比较?

Mysql查询开始后回滚

mysql - 将递归数据存储在一个或两个表中更好吗?

mysql 计数连接双结果

php - 如何在 html 表中填充 UNION ALL 查询数据