1. 程式人生 > >在mysql中查詢每個分組的前幾名

在mysql中查詢每個分組的前幾名

注意:!!!排序後分組出來的結果中非分組欄位是隨機的記錄中的資料,並不是按排序中的結果的第一條顯示的

  • 綜合推薦的兩種方式(已經測試了結果是可行的方案):

1.分組取前n條記錄

SELECT
b.id,
b.wx_user_id,
b.create_date,
b.type
FROM
t_weixin_user_browse b
WHERE
status = ‘A’
AND retailer_id = ‘fd23db2c9ed442b89754e94cbe437a81’
AND guide_id = ‘8536abcf952f4232b56eea5912dd575f’
AND (
SELECT
count(*)
FROM
t_weixin_user_browse t
WHERE
t.wx_user_id = b.wx_user_id
– (按時間倒序排,同一個使用者瀏覽時間不會出現重複的情況獲取最新n條瀏覽記錄)
AND t.create_date >= b.create_date
– (多個條件才能得出唯一的不重複的條件用這種方式)
– and CONCAT(t.create_date,t.type) >= CONCAT(b.create_date,b.type)
) <= 2;

2.分組取最新1條記錄(GROUP_CONCAT超過長度會進行擷取)

SELECT
b.id,
b.content,
b.type,
b.wx_user_id,
b.create_date
FROM
t_weixin_user_browse b
JOIN (SELECT
wx_user_id,
– (分組後按時間倒序的第一條記錄的id)
SUBSTRING_INDEX( GROUP_CONCAT(id ORDER BY create_date desc,type desc),’,’,1) id
FROM
t_weixin_user_browse
WHERE
status

= ‘A’
AND retailer_id = ‘fd23db2c9ed442b89754e94cbe437a81’
AND guide_id = ‘8536abcf952f4232b56eea5912dd575f’
GROUP BY
wx_user_id
) t on b.id = t.id
;