?explain select actor.first_name, actor.last_name, count(*) from (film_actor inner join actor on film_actor.actor_id = actor.actor_id) group by actor.actor_id\G; 與這個相比, 我的這種寫法的分析結果其實更好一點,區別就在于最后group by 的actor_id是用的actor的, 結果如下, 請問為何會這樣。
+----+-------------+------------+-------+---------------+---------+---------+-----------------------+------+-------------+
| id | select_type | table ? ? ?| type ?| possible_keys | key ? ? | key_len | ref ? ? ? ? ? ? ? ? ? | rows | Extra ? ? ? |
+----+-------------+------------+-------+---------------+---------+---------+-----------------------+------+-------------+
| ?1 | SIMPLE ? ? ?| actor ? ? ?| index | PRIMARY ? ? ? | PRIMARY | 2 ? ? ? | NULL ? ? ? ? ? ? ? ? ?| ? 15 | ? ? ? ? ? ? |
| ?1 | SIMPLE ? ? ?| film_actor | ref ? | PRIMARY ? ? ? | PRIMARY | 2 ? ? ? | sakila.actor.actor_id | ? 13 | Using index |
+----+-------------+------------+-------+---------------+---------+---------+-----------------------+------+-------------+
2015-12-01
同問
難道是主鍵的原因?
在actor表中actor_id是主鍵
而在film_actor表中('actor_id','film_id')組合作為主鍵
在兩個執行計劃的對比中看到
如果group by actor.actor_id
在查actor表時 用到了primary key
而?GROUP BY?film_actor.actor_id 時 沒有用到索引