56,679
社区成员
发帖
与我相关
我的任务
分享
/** 创建表结构 *********************************************************/
CREATE TABLE `a` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`a1` varchar(20) DEFAULT NULL,
`a2` varchar(20) DEFAULT NULL,
`a3` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `aaa` (`a1`,`a2`,`a3`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
/** 插入数据,可能要等一段时间 ****************************************/
BEGIN
declare i int ;
set i = 1;
while ( i <= 500000 ) do
insert into a (a1, a2,a3) values ('aaa',concat('test',i), adddate('2010-01-01',(rand(i)*36520) mod 3652));
set i = i+1;
end while;
while ( i <= 1000000 ) do
insert into a (a1, a2,a3) values ('bbb',concat('test',i-500000), adddate('2010-01-01',(rand(i)*36520) mod 3652));
set i = i+1;
end while;
END
看下面两条SQL:
1: select count(1) from (select 1 from a where a3 between '2010-01-01 00:00:00' and '2010-12-31 23:59:59' group by a1,a2) tmp;
2: select count(distinct a1,a2) from a where a3 between '2010-01-01 00:00:00' and '2010-12-31 23:59:59';
SQL1执行时间:2.313s
SQL2执行时间:3.062s
mysql> select count(*) from a;
+----------+
| count(*) |
+----------+
| 1000000 |
+----------+
1 row in set (0.00 sec)
mysql> select count(1) from (select 1 from a where a3 between '2010-01-01 00:00:
00' and '2010-12-31 23:59:59' group by a1,a2) tmp;
+----------+
| count(1) |
+----------+
| 99813 |
+----------+
1 row in set (2.08 sec)
mysql> select count(distinct a1,a2) from a where a3 between '2010-01-01 00:00:00
' and '2010-12-31 23:59:59';
+-----------------------+
| count(distinct a1,a2) |
+-----------------------+
| 99813 |
+-----------------------+
1 row in set (2.55 sec)
mysql>
mysql> create index bbb on a(a3);
Query OK, 1000000 rows affected (23.03 sec)
Records: 1000000 Duplicates: 0 Warnings: 0
mysql> select count(1) from (select 1 from a where a3 between '2010-01-01 00:00:
00' and '2010-12-31 23:59:59' group by a1,a2) tmp;
+----------+
| count(1) |
+----------+
| 99813 |
+----------+
1 row in set (1.50 sec)
mysql> select count(distinct a1,a2) from a where a3 between '2010-01-01 00:00:00
' and '2010-12-31 23:59:59';
+-----------------------+
| count(distinct a1,a2) |
+-----------------------+
| 99813 |
+-----------------------+
1 row in set (1.17 sec)
mysql>