SQL用DataDiff查询的怪现象而引发的思考(2)

来源:互联网 发布:卫衣品牌 知乎 编辑:程序博客网 时间:2024/05/16 05:20

在脑子里老是记得当初写SQL的时候,总是有人提醒对于主键的条件要写在前面,至于为什么现在总是记不清楚了。但是SQL中where 条件的执行顺序跟主键以及索引有很大的关系。

把上片中的表a 加上主键:

alter table

add constraint pk_a_id primary key (id)

 

然后在运行上篇中出错的例句:

select * from a where id in (1,3) and datediff(day, convert(datetime,val),getdate()) < 0

 

竟然没有错误,返回了id=1的记录。看来,如果表中有主键的话,主键会被优先执行的。所以此时id =2的记录根本就不在考虑范围之内。

 

 

假设我们不加主键,而是加上一个unique的index:

 

alter table a
drop constraint pk_a_id

 

create unique index u_a_id on a(id)

 

然后再运行上面的句子:

select * from a where   id in (1,3) and datediff(day, convert(datetime,val),getdate()) < 0

 

出现了错误:

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting datetime from character string.

 

 

可见index, 并不能改变where 条件的执行顺序,但是主键是可以的。

 

原创粉丝点击