如何根据mysql中的计数获得排名

时间:2016-11-08 09:29:11

标签: php mysql sql join count

我在根据计数获取排名时遇到问题。

我有两张桌子:

1)images
2)images_like

现在,如果images_like没有条目,那么它显示" NULL"在队伍中。请检查查询和输出:

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 

enter image description here

我需要显示3不为空....

提前致谢!!!!!

1 个答案:

答案 0 :(得分:0)

试试这样:

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