mysql - Sort comments by upvotes-downvotes, make sure ones without votes are displayed above negative -
i'm fetching comments , sorting them score (upvotes-downvotes
). if comment has not been voted on @ all, has null upvotes & downvotes, , ones negative displayed first.
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 )) comment_votes cv cv_commentid=comments.c_id ) upvotes, (select sum(if( cv.cv_type= '0', 1 , 0 )) comment_votes cv cv_commentid=comments.c_id ) downvotes comments inner join users on u_id = c_userid c_postid = ? , c_parentid = 0 order upvotes-downvotes desc limit 100
any way make sure ones without votes above ones negative?
just use coalesce()
function replace null
values 0
:
select c_id, c_text, c_date, c_parentid, u_username, coalesce((select sum(cv.cv_type = '1') comment_votes cv cv.cv_commentid= c.c_id ), 0) upvotes, coalesce((select sum(cv.cv_type = '0') comment_votes cv cv.cv_commentid = c.c_id ), 0) downvotes comments c inner join users u on u.u_id = c.c_userid c.c_postid = ? , c.c_parentid = 0 order upvotes - downvotes desc limit 100;
note: should use table aliases , qualified column names instead of naming columns in table prefix. instead of using c_parentid
, use c.parentid
. prefixes on column names useful, sql uses table aliases identify table column comes from.
Comments
Post a Comment