0

我有这个查询:

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领域的。感觉非常未优化,我需要帮助来解决如何实现它的不同方法。

它的作用是获取所有votetableID 等于 questions.id 的结果,如果表中的vote字段votes向上,则计为一,否则减一(因为显然它会向下)。

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

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

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

4

1 回答 1

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
于 2013-11-05T01:59:51.250 回答