天天看點

mysql多分組_mysql多種條件分組排序求某類最新一條

CREATE TABLE `test` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`name` varchar(255) CHARACTER SET latin1 DEFAULT NULL,

`category_id` int(11) DEFAULT NULL,

`date` datetime DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

這兩天讓一個資料查詢難了。主要是對group by 了解的不夠深入。才出現這樣的情況,後來網上學習了一下,并記錄下來分享給大家。這種需求,我想很多人都遇到過。下面是我模拟我的内容表

mysql多分組_mysql多種條件分組排序求某類最新一條

我現在需要取出每個分類中最新的内容

select * from test group by category_id order by `date`

結果如下

mysql多分組_mysql多種條件分組排序求某類最新一條

明顯。這不是我想要的資料,正确的SQL語句如下:

select a.* from test a where 1 > (select count(*) from test where category_id = a.category_id and date > a.date) order by a.name,a.date

寫的順序:select ... from... where.... group by... having... order by..

執行順序:from... where. .(order by(primary key) )..group by... having.... select ... order by...

是以在order by拿到的結果裡已經是分組的完的最後結果。

由from到where的結果如下的内容。

mysql多分組_mysql多種條件分組排序求某類最新一條

到group by時就得到了根據category_id分出來的多個小組

mysql多分組_mysql多種條件分組排序求某類最新一條
mysql多分組_mysql多種條件分組排序求某類最新一條

到了select的時候,隻從上面的每個組裡取第一條資訊結果會如下

mysql多分組_mysql多種條件分組排序求某類最新一條

即使order by也隻是從上面的結果裡進行排序。并不是每個分類的最新資訊。

回到我的目的上 --分類中最新的資訊

根據上面的分析,group by到select時隻取到分組裡的第一條資訊。有兩個解決方法

1,where+group by(對小組進行排序)

2,從form傳回的資料下手腳(即用子查詢)

由where+group by的解決方法

對group by裡的小組進行排序的函數我隻查到group_concat()可以進行排序,但group_concat的作用是将小組裡的字段裡的值進行串聯起來。

select group_concat(id order by `date` desc) from `test` group by category_id

再改進一下

select * from `test` where id in(select SUBSTRING_INDEX(group_concat(id order by `date` desc),',',1) from `test` group by category_id ) order by `date` desc

mysql多分組_mysql多種條件分組排序求某類最新一條

子查詢解決方案

select * from (select * from `test` order by `date` desc) `temp` group by category_id order by `date` desc

mysql多分組_mysql多種條件分組排序求某類最新一條

還可以這樣

SELECT * FROM test t WHERE date=(select MAX(date) from test where category_id=t.category_id) GROUP BY category_id order by `date` desc;

簡單結論:

當group by 與聚合函數配合使用時,功能為分組後計算

當group by 與having配合使用時,功能為分組後過濾

當group by 與聚合函數,同時非聚合字段同時使用時,非聚合字段的取值按照主鍵key升序第一個比對到的字段内容,即id小的條目對應的字段内容。

個人使用:

根據要求需要求表單關聯項目下,每個項目每年最新的一條表單資料。

外鍵ID vc_in_id ,vc_report_year 兩種類型進行分組 求最新一條,原始的group by  select會自動按照l_id從小到大取第一條資料不滿足。

正确做法先查詢結果,再加如下限制條件。

隻需要在查詢結果後面加上如下:

l_id in (

select SUBSTRING_INDEX(group_concat(l_id order by d_create_time desc),',',1) from fin_rep group by VC_INVEST_ID ,VC_REPORT_YEAR

)

最近新發現另一個分組求最新的方法 ,其中第一個limit 必須要用不然結果不對

select * from

(select * from val_calculate_result

order by l_id desc limit 100000)

as a group by a.vc_in_id

或者

select * from

(select * from val_calculate_result ,(select @rownum:=0) t

order by l_id desc )

as a group by a.vc_in_id

參考如下:

http://www.manongjc.com/article/1083.html

https://www.cnblogs.com/fps2tao/p/9038268.html

https://www.cnblogs.com/studynode/p/9861522.html