count和limit的奇淫巧技

当我们做项目的时候,发现有些数据表会非常的大。

这个时候难免会有需要查询某条数据存在不存在的时候。我们以往的方法就是通过count或者find查询是否存在这样的一条数据

就比如如下的mysql代码

####count方法
SELECT COUNT(*) from test where name = 'ctexthuang' and age = 1

####find方法
SELECT id from test where name = 'ctexthuang' and age = 1

然而我的i9+纯固态的mysql在百万级数量中查询都需要接近0.2秒左右。效率总得来说 是比较慢的。

测试

首先。我们用大量数据做个时间测试。先建表再添加百万条数据

####建表mysql
CREATE TABLE `test` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb3;

####存储过程添加数据
DROP PROCEDURE IF EXISTS myInsert;
CREATE PROCEDURE myInsert()
BEGIN
   DECLARE n int DEFAULT 1;
        loopname:LOOP
            INSERT INTO test(id,name,age)VALUES(n,'lilis',16);
            SET n=n+1;
        IF n=1000000 THEN
            LEAVE loopname;
        END IF;
        END LOOP loopname;
END;
CALL myInsert();

####再修改某条数据
UPDATE test set name = 'ctexthuang',age = 1 where id = 49081

然后。咱们再来看findcount的执行时间效率

####count方法
SELECT COUNT(*) from test where name = 'ctexthuang' and age = 1
#### 查询时间0.178s

####find方法
SELECT id from test where name = 'ctexthuang' and age = 1
#### 查询时间0.198s

最终就是奇淫巧技了

####limit方法
SELECT 1 FROM test where name = 'ctexthuang' and age = 1 limit 1
#### 查询时间0.008s

有人说count(主键)或者count(0)count(*)相比,count(0)count(主键)的速度要快很多。然而在百万数据的数据表上并没有比较出来这样的性能。

####count(0)方法
SELECT COUNT(0) from test where name = 'ctexthuang' and age = 1
#### 查询时间0.178s

####count(主键)方法
SELECT COUNT('id') from test where name = 'ctexthuang' and age = 1
#### 查询时间0.177s

由此可见count(0)count(主键)的性能与count(*)基本一致 而查询数据是否存在limit会更加的具有优势

tag(s): MySQL
show comments · back · home
Edit with Markdown
召唤看板娘