MySQL查询优化JOIN

时间:2010-05-01 09:18:18

标签: mysql optimization

我需要你的帮助来优化那些mysql查询,两者都在我的慢查询日志中。

SELECT a.nom, c.id_apps, c.id_commentaire, c.id_utilisateur,
       c.note_commentaire, u.nom_utilisateur
  FROM comments AS c
  LEFT JOIN apps AS a ON c.id_apps = a.id_apps
  LEFT JOIN users AS u ON c.id_utilisateur = u.id_utilisateur
 ORDER BY c.date_commentaire DESC LIMIT 5;

c.id_apps上有一个MySQL INDEX,a.id_apps,c.id_utilisateur,u.id_utilisateur和c.date_commentaire。

EXPLAIN结果:

id | select_type | table |  type  | possible_keys | key              | key_len | ref              | rows | Extra
1  | SIMPLE      |   c   |  index | NULL          | date_commentaire | 8       | NULL             | 119  |
1  | SIMPLE      |   a   | eq_ref | PRIMARY       | PRIMARY          | 3       | c.id_apps        | 1    |
1  | SIMPLE      |   u   | eq_ref | PRIMARY       | PRIMARY          | 3       | c.id_utilisateur | 1    |

SELECT a.id_apps, a.id_itunes, a.nom, a.prix, a.resume, c.nom_fr_cat, e.nom_edit
  FROM apps AS a
  LEFT JOIN cat AS c ON a.categorie = c.id_cat
  LEFT JOIN edit AS e ON a.editeur = e.id_edit
 ORDER BY a.id_apps DESC LIMIT 20;

EXPLAIN结果:

id | select_type | table |  type  | possible_keys |   key   | key_len | ref         | rows | Extra
1  | SIMPLE      |   a   |  index | NULL          | PRIMARY |    3    | NULL        | 5336 |  
1  | SIMPLE      |   c   | eq_ref | PRIMARY       | PRIMARY |    1    | a.categorie |  1   |  
1  | SIMPLE      |   e   | eq_ref | PRIMARY       | PRIMARY |    3    | a.editeur   |  1   |  

a.categorie上有一个MySQL INDEX,c.id_cat,a.editeur,e.id_edit和a.id_apps

由于

1 个答案:

答案 0 :(得分:0)

谢谢你们和他们抱歉,Marcelo这是我第一次使用Stackoverflow

使用EXPLAIN的第一个查询:

id select_type表类型possible_keys键key_len ref rows Extra

1 SIMPLE c index NULL date_commentaire 8 NULL 119
1 SIMPLE a eq_ref PRIMARY PRIMARY 3 c.id_apps 1
1 SIMPLE u eq_ref PRIMARY PRIMARY 3 c.id_utilisateur 1

第二个

id select_type表类型possible_keys键key_len ref rows Extra

1 SIMPLE索引NULL PRIMARY 3 NULL 5336
1 SIMPLE c eq_ref PRIMARY PRIMARY 1 a.categorie 1
1 SIMPLE e eq_ref PRIMARY PRIMARY 3 a.editeur 1