使用sql语法中in和or的功能差别
小弟最近使用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比较好。