2012-11-30 139 views
2

我遇到一個問題,我的查詢與一個組的通過。關於GROUP BY與ORDER BY

我有一個表download_category並下載。下載表中有一個名爲「thumb」的列(它是一個圖像 - varchar)。我想獲取類別的名稱並插入最後一個拇指。

我做這樣說:

SELECT download_category.id 
      , download_category.link 
      , download.thumb 
     FROM download 

RIGHT JOIN download_category ON (download_category.id = download.idCategoria) 
    WHERE download_category.link IN ('link-of-category') 

GROUP BY download_category.id 
     , download_category.link 
ORDER BY download.id DESC 

的RIGHT JOIN是必要的情況下不存在下載。

問題是:拇指列正在返回第一個插入的記錄,而不是最後一個「download.id DESC」。我究竟做錯了什麼?

回答

0

試試這個:

SELECT download_category.id 
     , download_category.link 
     , download.thumb 
from download_category 
left join (select max(id) maxId, 
        idCategoria 
      from download 
      group by idCategoria) t 
     ON (download_category.id = t.idCategoria) 
left join download 
     ON t.maxid=download.id 

WHERE download_category.link IN ('link-of-category') 

GROUP BY download_category.id 
     , download_category.link 
order by t.maxid DESC; 
+0

這個工作!謝謝! –