我有这张桌子:
// qanda
+----+----------------------------------------+---------+-----------+------+
| Id | body | related | user_id | free |
+----+----------------------------------------+---------+-----------+------+
| 1 | content of question1 | null | 2 | null |
| 2 | content of first answer for question1 | 1 | 2 | null |
| 3 | content of question2 | null | 6 | 300 |
| 4 | content of second answer for question1 | 1 | 4 | null |
| 5 | content of first answer for question2 | 3 | 2 | null |
| 6 | content of question3 | NULL | 8 | null |
| 7 | content of first answer for question3 | 6 | 4 | null |
| 8 | content of second answer for question3 | 6 | 2 | null |
+----+----------------------------------------+---------+-----------+------+
我有这个问题:
SELECT count(1)
FROM qanda question
JOIN qanda answer ON question.Id = answer.related
WHERE answer.related IS NOT NULL
AND answer.user_id = 2
AND question.free IS NULL;
如您所知,上面的查询会返回属于免费问题(在本例中为it returns 2
)的答案数。好的都好。我也有这张桌子:
// votes
+----+---------+-------+
| id | post_id | value |
+----+---------+-------+
| 1 | 2 | 1 |
| 2 | 3 | -1 |
| 3 | 2 | 1 |
| 4 | 8 | -1 |
| 5 | 1 | 1 |
| 6 | 4 | 1 |
| 7 | 2 | -1 |
| 8 | 8 | 1 |
| 9 | 8 | -1 |
| 10 | 8 | -1 |
+----+---------+-------+
我需要消除总得分为负的答案。因此在这种情况下它应该返回1
。因为在qanda.id = 8
处,该答案的总得票率为-2
,所以我不想算数。我怎么能这样做?
答案 0 :(得分:2)
排除总票数小于零的帖子的最简单方法是:
SELECT count(1)
FROM qanda question
JOIN qanda answer ON question.Id = answer.related
WHERE answer.related IS NOT NULL
AND answer.user_id = 2
AND question.free IS NULL
AND question.id not in (
select post_id
from votes
group by post_id
having sum(value) < 0)
此处的关键部分是having sum(value) < 0
选择具有净负投票的帖子。
来自评论......
找到有太多&#34;坏&#34;答案,你应该回报多少&#34; good&#34;他们做出的答案,并决定他们是否总体上是一个坏的&#34;用户。例如,有5个答案都是坏的用户与1000个答案的用户非常不同,其中只有5个是坏的,即使他们都有5个不良答案。
试试这个:
select
sum(score < 0) bad,
count(*) total,
sum(score < 0) / sum(.01) percent_bad
from (
SELECT coalesce(sum(value), 0) score
FROM qanda question
JOIN qanda answer ON question.Id = answer.related
LEFT JOIN votes ON votes.post_id = answer.id
WHERE answer.related IS NOT NULL
AND answer.user_id = 2
AND question.free IS NULL
AND answer.timestamp > subdate(now(), 365)
GROUP BY answer.id
) scores
关于SQL功夫的一些注释:
SUM(CASE ...)
表达式更容易编码,更容易阅读SUM(.01)
计算潜水(我只想到BTW)是获得百分比的最简单的方法,因为它不仅简化了表达式,而且还可以自动避免整数运算的回答舍入免责声明:代码可能无法编译或工作,因为它在我的手机上被翻阅(但它有合理的可能性)
答案 1 :(得分:0)
你可以放置另一个AND条件,并在其中有select语句(求和值,其中post id = qanda.id),用于计算总投票得分并将其评估为大于或等于零。
答案 2 :(得分:0)
请尝试一次:
SELECT v.value val
FROM qanda q
INNER JOIN qanda q1 ON q1.related = q.id
INNER JOIN votes v ON v.id = q.user_id
WHERE q.free IS NULL
AND q1.user_id = 2
AND v.value > 0