[MySQL] 當使用distinct/group by時產出的順序不是我們所需要

在做專案時很常會碰到要有個功能叫做 "瀏覽過的商品"

在我們系統是使用Log來做

使用Shopper_Id去Log中找出對應的商品ID,然後order by Timestamp desc

因為商品ID在Log中很容易重覆,所以可以使用distinct/group by來處理

但問題來了,明明有使用order by Timestamp desc,但順序卻不是我要的?

這是因為order by的欄位並不在我們的group by/distinct中

該如何解決?

使用order by MAX(Timestamp) desc就可以了

意思大概就是在我們Log中找Timestamp最大的來比對

更詳細的可以看國外高手的文章囉

So what is a workaround for this problem – in other words, how can we be more specific to get what we really want? Well, let’s rephrase the problem – what if we say we want to retrieve each salesperson ID sorted by their respective highest dollar amount value (and only have each salesperson_id returned just once)? This is different than just saying that we want each distinct salesperson ID sorted by their Amount, because we are being more specific by saying that we want to sort by their respective highest dollar amount value. Hopefully you see the difference.

From: http://www.programmerinterview.com/index.php/database-sql/sql-select-distinct-and-order-by/

留言

這個網誌中的熱門文章

[MySQL] schema 與資料類型優化

[翻譯] 介紹現代網路負載平衡與代理伺服器