通过upvotes-downvotes对评论进行排序,确保没有投票的评论显示在负面以上

时间:2016-02-08 12:21:08

标签: mysql sql

我提取评论并按照分数(upvotes-downvotes)对其进行排序。但是,如果评论没有被投票,那么它有NULL upvotes& downvotes,所以负面的将首先显示。

Upvotes为cv_type = 1,downvotes为cv_type = 0

SELECT c_id,c_text,c_date,c_parentid,u_username,
(select sum(IF( cv.cv_type=  '1', 1 ,  0 )) from comment_votes cv where cv_commentid=comments.c_id ) as upvotes,
(select sum(IF( cv.cv_type=  '0', 1 ,  0 )) from comment_votes cv where cv_commentid=comments.c_id ) as downvotes
FROM comments
INNER JOIN users
ON u_id = c_userid
WHERE c_postid = ? AND c_parentid = 0
ORDER BY upvotes-downvotes
DESC LIMIT 100

任何方式确保没有选票的人都是负面的?

1 个答案:

答案 0 :(得分:0)

只需使用coalesce()功能将NULL值替换为0

SELECT c_id, c_text, c_date, c_parentid, u_username,
       coalesce((select sum(cv.cv_type = '1') from comment_votes cv where cv.cv_commentid= c.c_id ), 0) as upvotes,
       coalesce((select sum(cv.cv_type = '0') from comment_votes cv where cv.cv_commentid = c.c_id ), 0) as downvotes
FROM comments c INNER JOIN
     users u
     ON u.u_id = c.c_userid
WHERE c.c_postid = ? AND c.c_parentid = 0
ORDER BY upvotes - downvotes DESC
LIMIT 100;

注意:您应该使用表别名和限定列名,而不是在带有前缀的表中命名列。不使用c_parentid,而是使用c.parentid。有时列名称上的前缀很有用,但SQL使用表别名来标识列来自的表。