gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:44:37 24 4
gpt4 key购买 nike

这是我的表的结构:

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com