日期:2014-05-18  浏览次数:20429 次

请教个问题:有没有比or效率更高的select语句?
select * from 商品 where( (商品类别=1) or (商品类别=2) or (商品类别=3) or (商品类别=6))
商品类别指的是粮食,五金,电子,蔬菜,水果,等等这样的类别
这个select语句看起来效率不是很高,有没有更高效的语句呢?

------解决方案--------------------
SQL code

select * from 商品 where 商品类别 in (1,2,3,6)

------解决方案--------------------
SQL code
select * from 商品 where 商品类别 in(1,2,3,6)

------解决方案--------------------
另建议尽量不要用"select *"的写法,

耐心写出需要返回的字段..
------解决方案--------------------
這類查詢只可用or 或 in

在商品类别列 建上索引
------解决方案--------------------
IN
Or
最终优化有都一样
------解决方案--------------------
建议用In吧,虽然效率差不多,但是你写太多or,自己头也晕
------解决方案--------------------
union all效率高点吧
------解决方案--------------------
探讨

IN
Or
最终优化有都一样

------解决方案--------------------
SQL code

create table test(id int identity(1,1),col varchar(100))
insert into test(col)
select top 10000 'a'  from sysobjects a cross join sysobjects b

--第一种情况
select * from test where id in (1,2,3,6)

--第二种情况
select * from test where id=1 or id=2 or id=3 or id=6

--第三种情况
select * from test where id=1 union all
select * from test where id=2 union all
select * from test where id=3 union all
select * from test where id=6

------解决方案--------------------

------解决方案--------------------
in或or 基本差不多。
------解决方案--------------------
用union all吧,效率高点
------解决方案--------------------
in 和 or 效率差不多吧....

------解决方案--------------------
同意maco_wang,用Ctrl+L,看執行計劃吧。
------解决方案--------------------
建了索引的话in和or的执行效率是一样的。
------解决方案--------------------
探讨
create table test(id int identity(1,1),col varchar(100))
insert into test(col)
select top 10000 'a' from sysobjects a cross join sysobjects b

--第一种情况
select * from test where id in (1,2,3,6)

--第二种情况
select * from test where id=1 or id=2 or id=3 or id=6

--第三种情况
select * from test where id=1 union all
select * from test where id=2 union all
select * from test where id=3 union all
select * from test where id=6

------解决方案--------------------
执行计划怎么比较?怎么看出前面2个和第3个比较,哪个效率更好?
------解决方案--------------------
SQL 语句优化原则:
1. IN 操作符
用IN写出来的SQL的优点是比较容易写及清晰易懂,这比较适合现代软件开发的风格。
但是用IN的SQL性能总是比较低的,从执行的步骤来分析用IN的SQL与不用IN的SQL有以下区别:
将其转换成多个表的连接,如果转换不成功则先执行IN里面的子查询,再查询外层的表记录,如果转换成功则直接采用多个表的连接方式查询。由此可见用IN的SQL至少多了一个转换的过程。一般的SQL都可以转换成功,但对于含有分组统计等方面的SQL就不能转换了。
推荐方案:在业务密集的SQL当中尽量不采用IN操作符。可以用exists代替。
SQL Server例子:
Exists用法:
select * from kj_dept where exists (select * from kj_dept_info where kj_dept.dept_id = dept_id and dept_id=XXX)
in用法:
select * from kj_dept where dept_id in (select dept_id from kj_dept_info where dept_id=XXX)