简体   繁体   中英

How to get rank according to count in mysql

I am getting issue with fetching the rank according to the count.

I have two tables :

1)images
2)images_like

Now if the images_like have no entries then it is showing "NULL" in the ranks. please check the query and output :

SELECT im.id, 
   rank 
FROM   (SELECT image_id, 
               @rownum := @rownum + 1 AS rank, 
               Count(*)               AS cnt 
        FROM   images_like, 
               (SELECT @rownum := 0) r 
        GROUP  BY image_id 
        ORDER  BY `cnt` DESC) AS d 
       RIGHT JOIN images AS im 
               ON d.image_id = im.id 

在此处输入图片说明

i need to display 3 not null ....

Thanks in advance !!!!!

Try like this :

SELECT im.id, d.rank  
FROM
(               
    SELECT t.image_id, @rownum := @rownum + 1 AS rank 
    FROM
        (               
          SELECT image_id, 
                 Count(*) AS cnt 
          FROM   images_like
          GROUP  BY image_id 
          ORDER  BY `cnt` DESC) AS d       
        ) t, 
     (SELECT @rownum := 0) r          
) d     
RIGHT JOIN images AS im ON d.image_id = im.id   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM