您可以使用優化程序跟蹤獲取有關優化程序如何執行查詢以及原因的更多信息。對於這種特殊的情況下,跟蹤不明確告訴多少次計數的計算方式,但我們可以得到有關用於執行聚合的臨時表的信息:
mysql> SET optimizer_trace='enabled=on';
Query OK, 0 rows affected (0,00 sec)
mysql> SELECT c2, COUNT(c2) FROM temp GROUP BY c2 HAVING COUNT(c2) > 1;
+------+-----------+
| c2 | COUNT(c2) |
+------+-----------+
| 1 | 2 |
| 2 | 2 |
+------+-----------+
2 rows in set (0,00 sec)
mysql> SELECT trace->'$.steps[*].join_execution.steps[*].creating_tmp_table'
-> FROM information_schema.optimizer_trace;
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| trace->'$.steps[*].join_execution.steps[*].creating_tmp_table' |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| [{"tmp_table_info": {"table": "intermediate_tmp_table", "location": "memory (heap)", "key_length": 5, "row_length": 23, "unique_constraint": false, "row_limit_estimate": 729444}}] |
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0,01 sec)
mysql> SELECT c2, COUNT(c2) AS c FROM temp GROUP BY c2 HAVING c > 1;
+------+---+
| c2 | c |
+------+---+
| 1 | 2 |
| 2 | 2 |
+------+---+
2 rows in set (0,00 sec)
mysql> SELECT trace->'$.steps[*].join_execution.steps[*].creating_tmp_table' -> FROM information_schema.optimizer_trace;
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| trace->'$.steps[*].join_execution.steps[*].creating_tmp_table' |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| [{"tmp_table_info": {"table": "intermediate_tmp_table", "location": "memory (heap)", "key_length": 5, "row_length": 14, "unique_constraint": false, "row_limit_estimate": 1198372}}] |
+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0,00 sec)
對於上面我們看到,當使用別名而不是重複COUNT表達式時,臨時表的行大小更小(14對23字節)。這表示對於您的查詢,在聚合期間計數已完成兩次。
使用'COUNT(*)',除非你想避免計算'employee_name IS NULL'的行數。 –