我有这个查询:
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
向上,则计为一,否则减一(因为显然它会向下)。
我试过不使用子查询并尝试
SUM( IF(votes.vote='up',1,-1) ) as votes
但是随着分组,结果变得非常错误。我也尝试过添加DISTINCT
,但这只是使所有值都变为-1或1。