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 |
+------+--------------+----------------+------+---------------+-----------+---------+-------+------+----------------+
请问这种优化方法正确吗?最后那一行是什么意思呢?
我对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 |
+------+--------------+----------------+------+---------------+-----------+---------+-------+------+----------------+
请问这种优化方法正确吗?最后那一行是什么意思呢?
解决方案 »
- 求高手教我mysql数据库主从同步,一台Linux 512M VPS送上!@@
- mysql只能显示1000条记录
- mysql中如何查询指定日期是否在一个日期区间中。
- mysql binlog
- MY SQL ADO驱动没有中国的吗?
- 怎么知道mysql使用什么中文编码(charsetEncoding)方式?或者说怎么设置中文编码方式?
- 求助:关于MySql如何实现与子查询相同的功能!!!
- 栏目与栏目信息复制SQL语句怎么写?谁帮我呢
- MyISAM高并发insert delete 该如何处理
- 查询每个team粉丝最多的三个国家两个分组,分别查询各显示三个最大数量
- mysql 插入千万级数据时,需要考虑哪些问题?
- MySQL如何查询数据插入时间?
至于第二条语句,有些错误在里面,这样产生的结果集会有重复的记录,即那些满足attack_id= 123 AND
defend_id= 123的行会出现两次(如果绝对不会存在这些行,那么没问题),LZ要么把UNION ALL改成UNION,要么给第二个UNION加一个条件:
select id,char_name from table_chara where attack_id= 123
union all
select id,char_name from table_chara where defend_id= 123 AND attack_id!=123
我推荐第二种改法(这个是《高性能MySQL》里的写法),不需要使用UNION,UNION相对于UNION ALL低效很多~