下面是多種寫法,針對使用group by后得到最新記錄的測試及結果:
說明:我在測試的時候,因為我的表數據在增加,得到最新的數據可能不同
1 -- 1、得到每個分組中id最小的那條記錄 2 select * from pic where point_code in('XX00024', 'XX00016', 'XX00025') and addtime > '2018-09-03' 3 group by point_code 4 -- 37033746 XX00016 長江大橋路口 http://xxx/10.58.237.73_01_20180903001241103.jpg 2018-09-03 00:12:41 5 -- 37033631 XX00024 沱六橋路口 http://xxx/10.25.77.3_01_20180903000355528.jpg 2018-09-03 00:03:55 6 -- 37033485 XX00025 高新區立交橋 http://xxx/10.210.98.143_01_20180903000211230.jpg 2018-09-03 00:02:11 7 8 -- 2、意圖,先通過子查詢,按照ID降序,得到每個分組中最新的一條記錄 9 select * from 10 ( 11 select * from pic where point_code in('XX00024', 'XX00016', 'XX00025') and addtime > '2018-09-03' order by id desc -- limit 1000 12 ) tt 13 group by point_code; 14 -- 結果還是每個分組最小的記錄,與第一種寫法結果相同 15 16 -- 3、在第二種寫法的子查詢周添加了一個limit,limit后面的數字大於你查詢的總條數即可 17 select * from 18 ( 19 select * from pic where point_code in('XX00024', 'XX00016', 'XX00025') and addtime > '2018-09-03' order by id desc limit 10000000000 20 ) tt 21 group by point_code; 22 -- 結果返回每個分組中最新的那條記錄 23 -- 37064239 XX00016 長江大橋路口 http://xxx/10.58.237.73_01_20180903144242037.jpg 2018-09-03 14:42:42 24 -- 37064240 XX00024 沱六橋路口 http://xxx/10.25.77.3_01_20180903143857383.jpg 2018-09-03 14:38:57 25 -- 37064139 XX00025 高新區立交橋 http://xxx/10.210.98.143_01_20180903143713651.jpg 2018-09-03 14:37:13 26 27 28 -- 4、在第一中寫法的group by后面添加一個desc 29 select * from pic where point_code in('XX00024', 'XX00016', 'XX00025') and addtime > '2018-09-03' 30 group by point_code desc 31 -- 返回結果是每個分組的最新記錄 32 -- 37064139 XX00025 高新區立交橋 http://xxx/10.210.98.143_01_20180903143713651.jpg 2018-09-03 14:37:13 33 -- 37064240 XX00024 沱六橋路口 http://xxx/10.25.77.3_01_20180903143857383.jpg 2018-09-03 14:38:57 34 -- 37064239 XX00016 長江大橋路口 http://xxx/10.58.237.73_01_20180903144242037.jpg 2018-09-03 14:42:42 35 36 -- 5、一般我們在查詢結果都會按照一定規則進行排序,對第四種寫法進行排序 37 select * from pic where point_code in('XX00024', 'XX00016', 'XX00025') and addtime > '2018-09-03' 38 group by point_code desc order by point_code 39 -- 返回結果又變成了每個分組的最小記錄了 40 -- 37033746 XX00016 長江大橋路口 http://xxx/10.58.237.73_01_20180903001241103.jpg 2018-09-03 00:12:41 41 -- 37033631 XX00024 沱六橋路口 http://xxx/10.25.77.3_01_20180903000355528.jpg 2018-09-03 00:03:55 42 -- 37033485 XX00025 高新區立交橋 http://xxx/10.210.98.143_01_20180903000211230.jpg 2018-09-03 00:02:11 43 44 -- 6、將第五種寫法的排序,放到分組外邊 45 select * from 46 ( 47 select * from pic where point_code in('XX00024', 'XX00016', 'XX00025') and addtime > '2018-09-03' 48 group by point_code desc 49 ) t order by point_code 50 -- 返回的結果又是每個分組的最新值 51 -- 37064239 XX00016 長江大橋路口 http://xxx/10.58.237.73_01_20180903144242037.jpg 2018-09-03 14:42:42 52 -- 37064240 XX00024 沱六橋路口 http://xxx/10.25.77.3_01_20180903143857383.jpg 2018-09-03 14:38:57 53 -- 37064139 XX00025 高新區立交橋 http://xxx/10.210.98.143_01_20180903143713651.jpg 2018-09-03 14:37:13
在使用group by希望得到最新的數據時,如果想采用子查詢先行排序,注意需要添加limit才會生效,這是我的測試結果
網上百度了一些,許多博客,沒有寫limit好像也生效了,不知道是不是mysql不同的版本問題。
好像只能針對單表進行這樣操作,表連接好像就沒有效果了