1. 程式人生 > 其它 >MySql Max函式和Group By 同時使用資料不一致問題記錄

MySql Max函式和Group By 同時使用資料不一致問題記錄

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

需求:

查詢出每個人2018年收藏量最高的專題資訊和專題數量

select t1.creatorId as puid,t1.course_Id,t1.`name`,resSubCount as 收藏量,MAX(t2.resSubCount) 
from mooc_subject t1 
	join mooc_subject_subscribeinfo t2 on t2.courseId =CONCAT(t1.course_Id)  
where published = 1 and status = 0 and createtime > '2018-01-01 00:00:00' and t2.cataid = 100000001 
GROUP BY t1.creatorId;

雖然也可以查詢出最大resSubCount,但是數值和其他自動根本對應不上,因為group by返回分組後的組內第一條資料資訊,max函式對應的是最大數量。

解決方法:

()括號內的sql按resSubCount DESC排序,外層sql分組得到第一條資料,即為最大數量資料,問題解決

select * from (select t1.creatorId as puid,t1.course_Id,t1.`name`,resSubCount as 收藏量 from mooc_subject t1 
	join mooc_subject_subscribeinfo t2 on t2.courseId =CONCAT(t1.course_Id)  
where published = 1 and status = 0 and createtime > '2018-01-01 00:00:00' and t2.cataid = 100000001 
ORDER BY t2.resSubCount DESC) as b 
GROUP BY b.puid;

轉載於:https://my.oschina.net/kdy1994/blog/2906917