Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4154484
  • 博文数量: 240
  • 博客积分: 11504
  • 博客等级: 上将
  • 技术积分: 4277
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-28 14:24
文章分类

全部博文(240)

分类: Mysql/postgreSQL

2008-02-12 12:57:18


用COUNT来查询一个表的记录多少,小的时候无所谓,记录多的时候速度就是个问题。
那天在PGSQL版里看到这个。总结一下。
此刻表引擎为MyISAM.
mysql> desc content;
+---------+------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |
+---------+------------+------+-----+---------+-------+

| cid | int(11) | NO | | 0 | |
| aid | int(11) | YES | | NULL | |
| content | mediumtext | YES | | NULL | |
+---------+------------+------+-----+---------+-------+

3 rows in set (0.02 sec)

mysql> select count(*) from content;
+----------+

| count(*) |
+----------+

| 208081 |
+----------+

1 row in set (0.05 sec)

更新为INNODB.
mysql> alter table content engine innodb;
Query OK, 208081 rows affected (2 min 19.80 sec)
Records: 208081 Duplicates: 0 Warnings: 0

mysql> select count(*) from content;
+----------+

| count(*) |
+----------+

| 208081 |
+----------+

1 row in set (33.99 sec)

新建立一个表专门存储记录的多少。如果要存放多个表的记录数目,以后增加相应的字段就可以了。
create table t_count (count_content int not null default 0);
insert into t_count(count_content) select count(*) from content;

DELIMITER $$
CREATE TRIGGER `tr_count_insert` AFTER INSERT on `content`
FOR EACH ROW BEGIN
  update t_count set count_content = count_content + 1;
END$$

DELIMITER ;

DELIMITER $$

CREATE TRIGGER `tr_count_delete` AFTER DELETE on `content`
FOR EACH ROW BEGIN
  update t_count set count_content = count_content - 1;
END$$
DELIMITER ;
这样虽然对数据更新操作有性能上的影响,不过查询速度就非常快了。因为这个表无论如何只有一条记录。
mysql> delete from content limit 1;
Query OK, 1 row affected (0.06 sec)

mysql> select count(*) from content;
+----------+

| count(*) |
+----------+

| 208080 |
+----------+

1 row in set (37.79 sec)

mysql> select count_content from t_count;
+---------------+

| count_content |
+---------------+

| 208080 |
+---------------+

1 row in set (0.01 sec)

阅读(4684) | 评论(3) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2008-04-15 15:49:06

lz对现象的描述是正确的。解决方法应该说不太妥当 innodb和myisam在count(*)的机制上略有不同。 当单纯count数据表,而不加where条件时。inno是全表扫一遍。 而myisam实现的机制和你所说相似。确实是保存了一个全局变量。 所以,myisam很快 两者在count语句有where时,机制一样,只要where的字段加了index,速度都很快。 比如,select count(*) from posts where id>0; 欢迎访问音乐八宝盒 http://www.8box.cn/user/ymruan

chinaunix网友2008-04-11 16:53:38

如果count带where条件的话,似乎不好办

chinaunix网友2008-03-14 11:21:19

It's good.