请,
我试图在几个不同的计数中获得用户获得积分的总价值,但一切都来自同一张桌子。
SQL:
SELECT o.author_id, SUM(o.vote_value) AS vote_value, n.best AS best_sum,
(SUM(o.vote_value) + (10 * n.best)) AS total
FROM comments o
LEFT JOIN (
SELECT COUNT(best) AS best, author_id
FROM comments
WHERE best = 1
GROUP BY author_id
) n ON o.author_id = n.author_id
GROUP BY o.author_id
ORDER BY total DESC
LIMIT 0, 4
问题是如果没有BEST(默认值为0,最好是1)我没有得到“total”和“best_sum”的任何内容。如果用户没有“最佳”,我需要0才能正确执行计算
对不起,我的英语不好,我想你会明白的 感谢
答案 0 :(得分:0)
如果最佳= NULL ,请考虑COALESCE
我假设你想要一个0值count(COALESCE(best,0) AS best)
答案 1 :(得分:0)
你应该使用COALESCE(n.best,0)
当第一个参数为NULL时,COALESCE返回第二个参数
SELECT o.author_id, SUM(o.vote_value) AS vote_value,
COALESCE(n.best, 0) AS best_sum,
(SUM(o.vote_value) + (10 * COALESCE(n.best, 0))) AS total
FROM comments o
LEFT JOIN (
SELECT COUNT(best) AS best, author_id
FROM comments
WHERE best = 1
GROUP BY author_id
) n ON o.author_id = n.author_id
GROUP BY o.author_id
ORDER BY total DESC
LIMIT 0, 4
答案 2 :(得分:0)
我认为你的问题是你过滤掉了最好不是1的行,所以它们不包含在组中。试试这个:
SELECT o.author_id, SUM(o.vote_value) AS vote_value, n.best AS best_sum,
(SUM(o.vote_value) + (10 * n.best)) AS total
FROM comments o
JOIN (
SELECT SUM(best) AS best, author_id
FROM comments
GROUP BY author_id
) n ON o.author_id = n.author_id
GROUP BY o.author_id
ORDER BY total DESC
LIMIT 0, 4
另外,也许我错过了一些东西,但不会这样做,保存子查询?
SELECT o.author_id, SUM(o.vote_value) AS vote_value, SUM(o.best) AS best_sum,
(SUM(o.vote_value) + (10 * SUM(o.best))) AS total
FROM comments o
GROUP BY o.author_id
ORDER BY total DESC
LIMIT 0, 4