gpt4 book ai didi

mysql - 在不同别名下计算同一张表上的同一列?

转载 作者:可可西里 更新时间:2023-11-01 08:44:54 24 4
gpt4 key购买 nike

我有两个表(好吧,3 个,一个是带有 ID、姓名、电子邮件等的用户表。但这是沼泽标准)。

表 1:

Questions:
id (auto inc)
user_id (INT)
question (text)
parent (INT)

表 2:

map_user_question_vote:
question_id (INT)
user_id (INT)
vote (INT)

这是一个问题和各种答案的网站。

所以一个用户发布了一个问题,parent 被设置为 0

当另一个用户发布回复时,它会转到同一个表,但父字段具有父问题的 ID。

每个用户都会看到一个针对问题和评论的投票按钮。 (没有否决或撤消)。

我需要做的是获得一条评论,找出它的投票总数,然后父问题的投票总数,所有这些都是针对单个用户

这是我目前所拥有的:

SELECT
questions.id
, questions.question
, COALESCE(SUM(qv.vote), 0) as question_vote_score
, COALESCE(SUM(cv.vote), 0) as comment_vote_score
, parent.id as parentId
, parent.title as parentQuestion

from `questions`

join `questions` as `parent` on `questions`.`parent` = `parent`.`id`

join `map_user_question_vote` as `cv` on
`cv`.`question_id` = `questions`.`id`

join `map_user_question_vote` as `qv` on
`qv`.`question_id` = `parent`.`id`

where questions.user_id = 1
and questions.parent > 0

group by questions.id

limit 5

发生了什么事,它似乎合并了所有“投票”总数,无论它们来自何处、问题或评论。

有没有 SQL 高手想帮我留头发? :)

编辑:添加 http://sqlfiddle.com/#!9/b5d08/1

最佳答案

如果您以这种方式连接表并在主查询中使用 group by,您将首先连接 map_user_question_vote 表的记录(两次)与 questions< 的记录 后面会针对相同的题组计算表和求和(虽然列名不同,但值是一样的)。

您需要加入子查询,首先计算投票的总和。即:

select
questions.id
, questions.question
, parent.id as parentId
, parent.question as parentQuestion
, COALESCE(qv.sum_vote, 0) as parent_question_vote_score
, COALESCE(cv.sum_vote, 0) as comment_vote_score

from `questions`

join `questions` as `parent` on
`questions`.`parent` = `parent`.`id`

left join (select `question_id`, sum(`vote`) as `sum_vote` from `map_user_question_vote` group by `question_id`) as `cv` on
`cv`.`question_id` = `questions`.`id`

left join (select `question_id`, sum(`vote`) as `sum_vote` from `map_user_question_vote` group by `question_id`) as `qv` on
`qv`.`question_id` = `parent`.`id`

where questions.user_id = 1
and questions.parent > 0

limit 5

查看 SQL fiddle 中的结果 here .

关于mysql - 在不同别名下计算同一张表上的同一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31567340/

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