MySql 中 count 与 limit 混用的后果

MySql中count与limit混用

文章来源: https://www.jianshu.com/p/7bb03f60b4ec

问题描述

  • version 5.7

  • 数据量: 100W

  • 目的: 利用select count查询表是否存在

  • 问题: 数据量大的时候select count也会慢(表无主键、唯一建,无索引),在count后增加limit不能得到预期结果

  • 原因: 因为limit的作用是限制返回结果。而count仅返回了一条数据,limit N 都将和没有limit结果一样

mysql> select count(*) from t1;
+----------+
| count(*) |
+----------+
|  1000000 |
+----------+
1 row in set (0.87 sec)
mysql> select count(*) from t1 limit 1;
+----------+
| count(*) |
+----------+
|  1000000 |
+----------+
1 row in set (0.74 sec)
-- count和limit组合得到的结果与count一致
-- 因为limit的作用是限制返回结果。而count仅返回了一条数据,limit N 都将和没有limit结果一样

为了让在大数据量的情况下使用count来判断表是否存在,执行的更快

解决办法1:

--- 嵌套子查询

mysql> select count(*) from (select * from t2 limit 1) a;
+----------+
| count(*) |
+----------+
|        1 |
+----------+
1 row in set (0.01 sec)

解决办法2:

--- 但上述情况中的select * 效果不好,改掉它
mysql> select count(*) from (select 1 from t2 limit 1) a;
+----------+
| count(*) |
+----------+
|        1 |
+----------+
1 row in set (0.00 sec)

解决办法3

-- 为什么要使用select 来判断表是否存在呢?
mysql> select TABLE_NAME from INFORMATION_SCHEMA.TABLES where table_schema = ‘zss‘
+------------+
| TABLE_NAME |
+------------+
| t2         |
+------------+
1 row in set (0.00 sec)

小彩蛋

-- 有很多的人都说count(*) 没有count(0)快。恰逢我又100W的一张表,我先来试试。 3次为准!!!

--------------------------- count(*) start ---------------------------
mysql> select count(*) from t2;
+----------+
| count(*) |
+----------+
|  1000000 |
+----------+
1 row in set (0.70 sec)

mysql> select count(*) from t2;
+----------+
| count(*) |
+----------+
|  1000000 |
+----------+
1 row in set (0.73 sec)
mysql> select count(*) from t2;
+----------+
| count(*) |
+----------+
|  1000000 |
+----------+
1 row in set (0.71 sec)
--------------------------- count(0) start ---------------------------
mysql> select count(0) from t2;
+----------+
| count(0) |
+----------+
|  1000000 |
+----------+
1 row in set (0.70 sec)

mysql> select count(0) from t2;
+----------+
| count(0) |
+----------+
|  1000000 |
+----------+
1 row in set (0.71 sec)

mysql> select count(0) from t2;
+----------+
| count(0) |
+----------+
|  1000000 |
+----------+
1 row in set (0.70 sec)
--------------------------- count(1) start ---------------------------

mysql> select count(1) from t2;
+----------+
| count(1) |
+----------+
|  1000000 |
+----------+
1 row in set (0.72 sec)

mysql> select count(1) from t2;
+----------+
| count(1) |
+----------+
|  1000000 |
+----------+
1 row in set (0.71 sec)

mysql> select count(1) from t2;
+----------+
| count(1) |
+----------+
|  1000000 |
+----------+
1 row in set (0.71 sec)

有人说count(0)和count(*)相比,count(0)的速度要快很多。再100W的数据表上并没有比较出来这样的性能。有人还会说,没有主键count(0)就会比较快。

下面是我的表信息,无索引,无主键。在100w的数据上也表现如上,并没有性能差异。

---- 该表无索引
mysql> show index from t2;
Empty set (0.01 sec)
---- 该表无主键
mysql> select table_schema, table_name,column_name from  INFORMATION_SCHEMA.KEY_COLUMN_USAGE  t where t.table_schema=‘t2‘;
Empty set (0.00 sec)

相关推荐