mysql - 像 '%%' 这样的列名和根本没有条件之间有区别吗?

标签 mysql query-optimization database-indexes

这两个查询有区别吗(优化方面)?

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/

相关文章:

搜索字段上的 SQL 索引,我应该包括 Id

mysql - 为表创建良好的索引

sql - 具有包含列的索引,有什么区别?

Mysql View 中的子查询非常慢

sql-server - 针对 View 加入 : performance issues

Hive Map-Join 配置之谜

MySQL Case Select 的行为不符合预期

php - 从mysql表中对刺客游戏中的玩家进行排名

javascript - 如何从 ajax 调用页面检索数据并将其设置为文本框?

php - 如何在 PHP 中使用 mySQL WHERE 子句?