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)