使用sql语法中in和or的功能差别

cxb1004 2003-07-18 12:29:25
小弟最近使用ms_sqlserver进行工作,遇到了这样一个问题,最后解决了,在这里拿出来大家讨论一下。
数据表结构:n_id(int 自增),n_type(varchar),n_title(varchar)...
查询要求:分页查询出n_type的值是'a','b','c'的n_id

错误语句:select top 6 n_id,n_title from tab_ebusiness where n_valid=1 and n_type='a'or n_type='b'or n_type='c' and n_id not in(select top 6 n_id from tab_ebusiness where n_valid=1 and n_type='a' or n_type='b' or n_type='c' order by n_id desc) order by n_id desc

正确语句:select top 6 n_id,n_title from tab_ebusiness where n_valid=1 and n_type in ('a','b','c') and n_id not in(select top 6 n_id from tab_ebusiness where n_valid=1 and n_type in ('a','b','c') order by n_id desc) order by n_id desc

注释:括号语句中的6是翻页以后形成的数据;按照这个条件查询出来有7条记录,我设置一页显示6条记录,但是翻页以后形成的错误语句使得查询记录还有6条(应该只有一条)。

or的作用是将并列的值进行“或”操作,与in在一定程度上有相似地方。但是在对于同一个字段来说,使用or就是增加了查询条件,将查询的条件累加上去,查询的结果就会出错。因此以后各位遇到同一个字段的多个值并存的情况,还是使用in比较好。
...全文
568 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
eastpond 2003-07-18
  • 打赏
  • 举报
回复
小弟最近使用ms_sqlserver进行工作,遇到了这样一个问题,最后解决了,在这里拿出来大家讨论一下。
数据表结构:n_id(int 自增),n_type(varchar),n_title(varchar)...
查询要求:分页查询出n_type的值是'a','b','c'的n_id

错误语句:select top 6 n_id,n_title from tab_ebusiness where n_valid=1 and n_type='a'or n_type='b'or n_type='c' and n_id not in(select top 6 n_id from tab_ebusiness where n_valid=1 and n_type='a' or n_type='b' or n_type='c' order by n_id desc) order by n_id desc
其实上面的错误语句只要加上括号就可以了,如下:
select top 6 n_id,n_title from tab_ebusiness where n_valid=1 and (n_type='a'or n_type='b'or n_type='c') and n_id not in(select top 6 n_id from tab_ebusiness where n_valid=1 and (n_type='a' or n_type='b' or n_type='c') order by n_id desc) order by n_id desc


其实 in 跟 or 是一样的,sqlserver在处理in时,会把in转换成or处理,从效率上来说可能还是or快一点
Keown 2003-07-18
  • 打赏
  • 举报
回复

where (condtion1 or condition2 or condition3) and (condtion4 or condition5)..

和下面的比较一下

where condtion1 or condition2 or condition3 and condtion4 or condition5...
<=>
where condtion1 or condition2 or (condition3 and condtion4) or condition5...

条件不同,结果当然不同了

in和or达到相同的效果
但where tempfield in (select field1 from table1)的功能更强,可以筛选出记录集中的数据 or 来连接只能穷举?
jiutiao 2003-07-18
  • 打赏
  • 举报
回复
in 和 or 一样,
in 有些集合的意思,可对集合中的数据进行比较
or 对已知条件比较

如: select * from table where field =5 or field=6
select * from table where field in(5,6)
select * from table where field in(select field from ...)

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧