某种类型和分类的SQL查询

时间:2014-09-24 22:22:46

标签: mysql sql

我正在查询的模型:( stackoverflow的基本版本)

http://i.stack.imgur.com/210dv.png

我正在尝试执行以下SQL查询: 对于特定用户(例如用户3982),他们收到的关于问题答案的净票数 在每个标签中。

我有以下查询,但在每个COUNT中我不确定如何在计数之外选择相同的标记时从tags.tag_description中选择正确的标记。

通过推荐编辑反映集团

到目前为止,这是我的查询:

SELECT tag_description, 
    (SELECT COUNT(vote.vote_id) 
    FROM vote 
    JOIN answervote USING (vote_id)
    JOIN answers USING (answer_id)
    JOIN questions USING (question_id)
    JOIN tags USING (question_id)
    WHERE vote.vote_choice = 'u' 
    AND  vote.vote_id = answervote.vote_id 
    AND answervote.answer_id = answer.answer_id
    AND tags.question_id = questions.question_id
    GROUP BY tag.tag_description)

  -(SELECT COUNT(vote_choice) 
    FROM vote 
    JOIN answervote USING (vote_id)
    JOIN answers USING (answer_id)
    JOIN questions USING (question_id)
    JOIN tags USING (question_id)
    WHERE vote.vote_choice = 'd'
    AND  vote.vote_id = answervote.vote_id 
    AND answervote.answer_id = answer.answer_id
    AND tags.question_id = questions.question_id
    GROUP_BY tags.tag_description) AS total_points

FROM tags
JOIN questions USING (question_id)
JOIN user USING (user_id)
WHERE user.user_id = 3982
GROUP BY tags.tag_description;

1 个答案:

答案 0 :(得分:0)

在这种情况下,您可以使用称为条件聚合的技巧来消除内部选择:

select
    tag_description,
    sum(case
        when vote.vote_choice = 'u' then 1
        when vote.vote_choice = 'd' then -1
    else 0 end) as total_points
from
    vote
        join
    answervote
        using (vote_id)
        join
    answers
        using (answer_id)
        join
    questions
        using (question_id)
        join
    tags
        using (question_id)
where
    questions.user_id = 3982
group by
    tags.tag_description;