SQL查询w / Net#Votes

时间:2013-11-05 01:45:11

标签: mysql sql query-optimization

我有这个问题:

SELECT   (COUNT (questions.id) / 10) AS totalPages,
          COUNT (DISTINCT answers.id) AS answers,
          COUNT (DISTINCT views.id) AS views,
                (SELECT(COUNT (if (votes.vote = 'up', 1, NULL)) - COUNT (if (votes.vote = 'down', 1, NULL)))
                   FROM   votes
                  WHERE   table = 'questions' AND tableId = questions.id) AS votes
FROM               questions
                LEFT JOIN
                   users
                ON questions.USER = users.id
             LEFT JOIN
                answers
             ON questions.id = answers.question
          LEFT JOIN
             views
          ON questions.id = views.question
       LEFT JOIN
          votes
       ON questions.id = votes.tableId AND votes.table = 'questions'
GROUP BY   questions.id
ORDER BY   questions.date DESC
LIMIT :limit

这篇文章的主题是关于votes字段。感觉非常不优化,我想要帮助解决如何实现它的不同方法。

它的作用是vote的tableID等于questions.id所有结果,如果vote表中的votes字段为up,它算作一个,否则减去一个(因为它显然会减少)。

我尝试过不使用子查询并尝试

SUM( IF(votes.vote='up',1,-1) ) as votes

但随着分组,结果变得非常错误。我也尝试添加DISTINCT,但只是将所有值设为-1或1。

1 个答案:

答案 0 :(得分:0)

我不确定你需要SELECT部分​​中的子查询。试试这个:

SELECT 
    count(questions.id)/10 AS totalPages, 
    count(DISTINCT answers.id) as answers, 
    count(DISTINCT views.id) as views, 
    count(if(votes.vote='up', 1, null)) - count(if(votes.vote='down', 1, null))) as votes 
FROM 
    questions 
        LEFT JOIN users ON questions.user=users.id 
        LEFT JOIN answers ON questions.id=answers.question 
        LEFT JOIN views ON questions.id=views.question 
        LEFT JOIN votes ON questions.id=votes.tableId AND votes.`table`='questions' 
GROUP BY questions.id 
ORDER BY questions.date DESC 
LIMIT :limit