+ -
当前位置:首页 → 问答吧 → 关于MYSQL中OR语句有关的优化问题

关于MYSQL中OR语句有关的优化问题

时间:2011-07-30

来源:互联网

select id,char_name from table_chara where attack_id= 123 or defend_id= 123
我对attack_id和defend_id分别设置了Normal类型的索引
这样子搞的话是全盘扫描,对吧?

照网上的做法,用union all的办法,将上面改成:
select id,char_name from table_chara where attack_id= 123 union all select id,char_name from table_chara where defend_id= 123

我通过explain分析,得出下面的结果:
+------+--------------+----------------+------+---------------+-----------+---------+-------+------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+--------------+----------------+------+---------------+-----------+---------+-------+------+----------------+
| 1 | PRIMARY | log_pet_battle | ref | attack_id | attack_id | 8 | const | 1 | |
| 2 | UNION | log_pet_battle | ref | defend_id | defend_id | 9 | const | 4 | Using where |
| NULL | UNION RESULT | <union1,2> | ALL | NULL | NULL | NULL | NULL | NULL | Using filesort |
+------+--------------+----------------+------+---------------+-----------+---------+-------+------+----------------+


请问这种优化方法正确吗?最后那一行是什么意思呢?

作者: moumouguo   发布时间: 2011-07-30

你的方法可以。最后一行是合并两个结果集。

作者: ACMAIN_CHM   发布时间: 2011-07-30