我有这个问题:
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。
答案 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