我正在获取评论并按分数对它们进行排序 (upvotes-downvotes
)。然而,如果一条评论根本没有被投票,那么它有 NULL 赞成票和反对票,所以负面的将首先显示。
赞成票是cv_type = 1
,反对票是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
有什么方法可以确保没有投票的人高于反对的人?
最佳答案
只需使用 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 使用表别名来标识列来自哪个表。
关于mysql - 按赞成票-反对票对评论进行排序,确保没有投票的评论显示在否定上方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35269584/