在不同的别名下计算同一个表中的同一列?

时间:2015-07-22 15:19:08

标签: mysql join

我有两个表(好吧,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)

这是一个问题和各种anwsers网站。

因此,用户发布了一个问题,并且父级设置为0

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

每个用户都会收到有关问题和评论的投票按钮。 (没有downvoting或撤消)。

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

这是我到目前为止所做的:

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

2 个答案:

答案 0 :(得分: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小提琴here中查看结果。

答案 1 :(得分:0)

我不确定我是否做对了,但我想,这可能就是你要找的东西:

SELECT
    q.id,
    q.user_id,
    q.question,
    SUM(IF(q.parent > 0, cv.vote, 0)) as comment_vote,
    SUM(IF(q.parent = 0, cv.vote, 0)) as question_vote
FROM map_user_question_vote as cv
INNER JOIN questions as q ON q.id = cv.question_id
WHERE q.user_id = 1
GROUP BY q.id, q.user_id, q.parent
;

http://sqlfiddle.com/#!9/b5d08/5