当前位置: 首页 > 图文教程 > 数据库 > MYSQL > 索引对查询条件顺序的影响

MYSQL
数据库新手入门之MySQL中如何定义外键
MySQL ODBC进行MySQL和SQL Server转换
三方法优化MySQL数据库查询
意料外的MySQL运算符可获更多数据功能
Sql Server 2005 数据库维护计划
搞定MySQL数据库中文模糊检索问题
MySQL服务器内部安全数据目录如何访问
SECURITY INVOKER存储过程权限提升漏洞
MySQL常见错误提示及解决方法
MySQL 5 C API 访问数据库例子程序
管理员必读10个重要MySQL客户启动选项
通过rpm包安装、配置及卸载mysql
实现MySQL数据库数据的同步方法介绍
六大步保护MySQL数据库中重要数据
MySQL数据库的内部以及外部安全性简介
MySQL数据库的数据备份与恢复学习
Java连接各种数据库的实例
UNIX设置MySql数据同步 实现复制功能
扩展求方差的mysql函数例子
MySQL 事务预编译查询和Perl DBI简化

MYSQL 中的 索引对查询条件顺序的影响


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 89 ::
收藏到网摘: n/a

  一则"表的索引影响查询条件顺序"示例

-------------------------------------------------------------------------

  环境:Sql Server2000 +sp4

  问题:

  select datediff(day,'20040910','20040920')  --这句可以执行

--而下面这句不能执行(有时也可以执行)
--sub_para为varchar(8),错误信息是:从字符串转换为 datetime 时发生语法错误。
select * from T_SUB
where item_local_code='03004'
 and  datediff(day,sub_para,getdate())=29
 and (sub_del_flag<>1)

--而且不能执行的时候,这个语句不会返回任何记录集
select * from t_sub
where  item_local_code='03004'
 and isDate(sub_para)=0

-------------------------------------------------------------------------

--原因,表中创建的索引影响了条件的执行顺序
--导致先执行了 datediff(day,sub_para,getdate())

--下面的测试说明了这个问题
--测试表及数据
create table tb(
item_local_code char(5),
sub_del_flag int,
sub_para varchar(10),
constraint PK_t primary key(sub_para,item_local_code)
)
insert tb select '03004',1,'2003-1-1'
union all select '03005',1,'2003a1-1'
go

--查询语句
select * from (
 select * from tb
 where item_local_code='03004'
  and sub_del_flag<>0
  and isdate(sub_para)=1
) A where datediff(day,sub_para,getdate())>29
go

--删除测试
drop table tb

/*--测试结果

item_local_code sub_del_flag sub_para  
--------------- ------------ ----------
03004           1            2003-1-1

服务器: 消息 241,级别 16,状态 1,行 3
从字符串转换为 datetime 时发生语法错误。

--*/