这两个查询有区别吗(优化方面)?
select * from users;
和
select * from users where first_name like '%%' and last_name like '%%'
我正在使用传递的参数动态地在 PHP 中构建查询。 因此,例如..
$first_name_str = "";
if($firstname)
{
$first_name_str = "first_name = '%".$firstname."%' and";
}
$last_name_str = "";
if($lastname)
{
$last_name_str = "last_name = '%".$lastname."%' and";
}
$query =
"select
*
from
users
where
".$first_name_str."
".$last_name_str."
1=1";
我问这个问题的原因是因为我读到mysql在执行选择时仅使用一个索引。因此,如果我对名字和姓氏有单独的索引,则只会使用一个索引。如果我的查询为:
select * from users where first_name like '%%' and last_name like '%%'
默认情况下,我可以在名字和姓氏上添加串联索引,搜索会更快?
最佳答案
喜欢“%”与喜欢“%%”或喜欢“%%%”或喜欢“%%%%”相同。
要亲自检查这一点,只需对查询运行解释即可。下面是我在 table 上运行的一些示例查询。
mysql> explain select * from USERS where EMAIL like '%';
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | USERS | ALL | NULL | NULL | NULL | NULL | 415 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1 row in set (0.02 sec)
mysql> explain select * from USERS where EMAIL like '%%';
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | USERS | ALL | NULL | NULL | NULL | NULL | 415 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1 row in set (0.00 sec)
mysql> explain select * from USERS where EMAIL like '%%%';
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | USERS | ALL | NULL | NULL | NULL | NULL | 415 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1 row in set (0.01 sec)
@Iain 的 2 点是提高性能的正确方法。 但尝试使用负载测试来定位暂存中的大多数性能问题。
关于mysql - 像 '%%' 这样的列名和根本没有条件之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5102218/