将使用这些查询跟踪索引

时间:2013-06-18 23:18:05

标签: php mysql indexing

我正在创建一个客户表,我需要索引中的4个字段。 这是表结构。

id,userName,status,email,password,fullName,joinDate (id是autoIncrement和primary key)

Index中的4个字段是: userName,status,email,password

我需要运行的查询是:

select id from table where status='active' and email='emailId' and password='pass' limit 1

select id from table where userName='user' and status='active' limit 1

select fullName from table where id='123' limit 1

我想知道所有这些查询是否会遵循索引? 如果不是,我如何更改结构以便遵循索引?我正在使用mysql和php。

由于

2 个答案:

答案 0 :(得分:0)

按照这个顺序,我受过教育的猜测是“不”,“是”和“否”。但如果你有tools that answer the question and measure the performance,那么猜测是愚蠢的。

  

如何更改结构以便遵循索引?

这完全是倒退。数据库结构本质上是您的公共API。不要改变结构;改变指数。

以下是您的查询以及可能运行良好的索引。 (您不仅限于单个索引。但不要相信“可能运行良好”;请使用EXPLAIN进行测量。)

select id 
from table 
where status='active' 
  and email='emailId' 
  and password='pass' limit 1;

create index on table (status, email, password);

此查询(上面)可能不会使用现有索引,因为第一列 - userName - 未在WHERE子句中使用。

select id 
from table 
where userName='user' 
  and status='active' limit 1;

现有索引用于此查询,只要您按实际顺序列出索引中的列即可。 (WHERE子句中的两列与索引中的前两列匹配。)使用EXPLAIN验证。

select fullName 
from table 
where id='123' limit 1;

列“id”是主键;它已经有一个索引。

看起来你只需“在{状态,电子邮件,密码}上添加索引。

MySQL multiple column indexes

答案 1 :(得分:0)

是的,你的索引是好的。我喜欢用php来验证一些字段只是一个字段查询。但是您应该考虑将状态更改为数字tinyint(1)或char(1)并使用1 =有效,2 =无效,3 =禁用,4 =禁止

select id,status,password from table where email='emailId' limit 1

$db_rows = mysql_num_rows($result); // $db->num_rows;

if($row['status']=='active' &&  $row['password']==$pass && $db_rows==1){do stuff}

select id,status from table where userName='user' limit 1

if($row['status']=='active' && $db_rows==1){do stuff}

select fullName from table where id='123' limit 1