mysql group by 先排序與分組同時使用方法

來源:互聯網
上載者:User

本教程今天要講述一下關於,困擾使用mysql教程資料庫教程的朋友的一個常見的問題,mysql group by 先排序與分組同時使用方法,下面看執行個體。

看排序

select * from (select * from posts order by dateline desc) group by  tid order by dateline desc limit 10


這樣效率應該高點。取消了order   by   的filesort過程。

select   *   from   t   where     logtime     in   (select   max(logtime   )   from   t   group   by   username)


 

也有網友利用自串連實現的 ,這樣的效率應該比上面的子查詢效率高,不過,為了簡單明了,就只用這樣一種了,group by沒有排序功能,可能是mysql弱智的地方,也許是我還沒有發現


--
-- 表的結構 `test`
--

create table if not exists `test` (
  `id` int(11) not null auto_increment,
  `name` varchar(16) not null,
  `month` int(11) not null,
  `serial` int(11) not null,
  `other` varchar(20) not null,
  primary key (`id`)
) engine=myisam  default charset=utf8;

--
-- 匯出表中的資料 `test`
--

insert into `test` (`id`, `name`, `month`, `serial`, `other`) values
(1, 'a', 200807, 2, 'aaa1'),
(2, 'a', 200805, 2, 'aaa2'),
(3, 'b', 200805, 3, 'bbb3'),
(4, 'b', 200805, 4, 'bbb4'),
(5, 'a', 200805, 1, 'aaa5'),
(6, 'c', 200807, 5, 'ccc6'),
(7, 'b', 200807, 8, 'bbb7'),
(8, 'c', 200807, 3, 'ccc8'),
(9, 'a', 200805, 6, 'aaa9');

查詢
select * from (select * from test order by month desc,serial desc) t group by name
得到
id     name     month     serial     other
1     a     200807     2     aaa1
7     b     200807     8     bbb7
6     c     200807     5     ccc6
換一下排序方式
select * from (select * from test order by month asc,serial desc) t group by name
得到
id     name     month     serial     other
9     a     200805     6     aaa9
4     b     200805     4     bbb4
6     c     200807     5     ccc6
都按我們的要求顯示了結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.