发布于 2016-01-14 13:26:35 | 226 次阅读 | 评论: 0 | 来源: PHPERZ

这里有新鲜出炉的Mysql教程,程序狗速度看过来!

Mysql关系型数据库管理系统

MySQL是一个开放源码的小型关联式数据库管理系统,开发者为瑞典MySQL AB公司。MySQL被广泛地应用在Internet上的中小型网站中。由于其体积小、速度快、总体拥有成本低,尤其是开放源码这一特点,许多中小型网站为了降低网站总体拥有成本而选择了MySQL作为网站数据库。


本教程今天要讲述一下关于,困扰使用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
都按我们的要求显示了结果



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务