優化總結:
1.任何情況下SELECT COUNT(*) FROM xxx 是最優選擇;
2.盡量減少SELECT COUNT(*) FROM xxx WHERE COL = ‘xxx’ 這種查詢;
3.杜絕SELECT COUNT(COL) FROM tablename WHERE COL = ‘xxx’ 的出現。(其中COL非主鍵)
環境:
MySQL版本:5.0.45
OS:Windows XP SP3
數據表一:sphinx
+―――-+――――――+――+―C+―――+―――――-+
| FIEld | Type | Null | Key | Default | Extra |
+―――-+――――――+――+―C+―――+―――――-+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| til | varchar(100) | NO | | | |
| content | text | NO | | | |
| dataline | int(11) | NO | | | |
+―――-+――――――+――+―C+―――+―――――-+
記錄數:1120100
查詢一:
MySQL> select count(*) as totalnum from sphinx;
+―――-+
| totalnum |
+―――-+
| 1120100 |
+―――-+
1 row in set (0.00 sec)
查詢二:
MySQL> select count(*) as totalnum from sphinx where id>1000;
+―――-+
| totalnum |
+―――-+
| 1119100 |
+―――-+
1 row in set (2.17 sec)
查詢三:
MySQL> select count(*) as totalnum from sphinx where id>1000;
+―――-+
| totalnum |
+―――-+
| 1119100 |
+―――-+
1 row in set (0.61 sec)
查詢四:
MySQL> select count(*) as totalnum from sphinx where id>1000;
+―――-+
| totalnum |
+―――-+
| 1119100 |
+―――-+
1 row in set (0.61 sec)
查詢五:
MySQL> select count(id) as totalnum from sphinx;
+―――-+
| totalnum |
+―――-+
| 1120100 |
+―――-+
1 row in set (0.00 sec)
查詢六:
MySQL> select count(til) as totalnum from sphinx where id>1000;
+―――-+
| totalnum |
+―――-+
| 1119100 |
+―――-+
1 row in set (1 min 38.61 sec)
查詢七:
MySQL> select count(id) as totalnum from sphinx where id>11000;
+―――-+
| totalnum |
+―――-+
| 1109100 |
+―――-+
1 row in set (0.61 sec)
查詢八:
MySQL> select count(id) as totalnum from sphinx;
+―――-+
| totalnum |
+―――-+
| 1120100 |
+―――-+
1 row in set (0.03 sec)
結論:
在 select count() 沒有 where 條件的時候 select count(*) 和 select count(col) 所消耗的查詢時間相差無幾。
在 select count() 有 where 條件的時候 select count(col) 所消耗的查詢時間 比 select count(*) 明顯多出數量級的時間。