1
我有一個用戶生成內容的表格,其中包含狀態的ENUM格式列。 (待定,已批准,已批准,汽車,或拒絕)爲了保持連接的眼睛對狀態的最新內容的數量,我使用以下查詢:在使用SUM時提高MySQL查詢性能
mysql> SELECT DATE(dt_submitted) AS date,
COUNT(*) AS count,
SUM(IF(status='Approved', 1, 0)) as approved,
SUM(IF(status='Approved-auto', 1, 0)) as approved_auto,
SUM(IF(status='Rejected', 1, 0)) as rejected,
SUM(IF(status='Pending', 1, 0)) as pending
FROM post
WHERE dt_submitted > DATE_SUB(CURDATE(), INTERVAL 30 DAY)
GROUP BY date;
+------------+-------+----------+---------------+----------+---------+
| date | count | approved | approved_auto | rejected | pending |
+------------+-------+----------+---------------+----------+---------+
| 2011-11-22 | 131 | 124 | 0 | 7 | 0 |
| 2011-11-23 | 116 | 114 | 0 | 2 | 0 |
...
| 2011-12-21 | 690 | 674 | 5 | 11 | 0 |
| 2011-12-22 | 80 | 75 | 0 | 4 | 38 |
+------------+-------+----------+---------------+----------+---------+
31 rows in set (0.60 sec)
這幾乎是完美的,但我很挑剔,想看看我能不能做得更快。 (在這臺服務器上0.6秒很慢,並且表變化太頻繁,無需擔心將靜態日期傳遞給緩存結果。)
如果我解釋查詢,它沒有使用任何索引(status
已索引)。 (難道這是因爲它引用了總和創建臨時表?)
explain SELECT DATE(dt_submitted) AS date, COUNT(*) AS count, SUM(IF(status='Approved', 1, 0)) as approved, SUM(IF(status='Approved-auto', 1, 0)) as approved_auto, SUM(IF(status='Rejected', 1, 0)) as rejected, SUM(IF(status='Pending', 1, 0)) as pending FROM post WHERE dt_submitted > DATE_SUB(CURDATE(), INTERVAL 30 DAY) GROUP BY date;
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------------------------------------+
| 1 | SIMPLE | post | ALL | NULL | NULL | NULL | NULL | 529902 | Using where; Using temporary; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+--------+----------------------------------------------+
1 row in set (0.00 sec)
那麼,有什麼我可以做優化表或重寫查詢,使這個更快?或者這個查詢是否受限於可用系統資源的速度?
編輯:dt_submitted
沒有索引。
您可以發佈您的索引創建語句? – 2011-12-22 17:34:07
聖牛我是個白癡。當我看到dt_submitted實際上沒有被索引時,即將發佈SHOW CREATE。創建索引將時間縮短到0.1秒。 (現在我應該刪除這個問題,或者我該如何最好地處理該問題?) – 2011-12-22 17:48:48
爲該問題創建一個答案 – Ben 2011-12-22 17:56:56