2016-11-08 60 views
0

我得到問題,根據計數提取排名。如何獲得排名根據計數在mysql

我有兩個表:

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顯示NOT NULL ....

謝謝!!!!!

+0

見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me一個非常簡單的sql查詢 - 順便說一句,注意RIGHT JOINs是極其罕見的。 – Strawberry

+0

請在表格中提供示例數據 – Viki888

回答

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 
+0

謝謝,但無法正常工作! –