关于带有ORDER BY的GROUP BY

时间:2012-11-30 13:59:51

标签: group-by sql-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。

问题是:thumb列返回第一个插入的记录,而不是最后一个“download.id DESC”。我做错了什么?

1 个答案:

答案 0 :(得分: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;