问个SQL中or和and的问题

SilverNet 2009-12-07 11:28:50
创建表语句

if object_id('tandor') is not null drop table tandor
create table tandor
(
id int identity(1,1),
username varchar(20),
deptname varchar(20),
compname varchar(20)
)
insert tandor select '张三','技术部','广州分公司'
union all select '李四','技术部','广州分公司'
union all select '李五','市场部','广州分公司'
union all select '李六','业务部','佛山分公司'
union all select '李七','信息部','佛山分公司'


我现在想查出表中部门为“技术部”,或者公司为“广州分公司的”数据,并且实现分页效果,于是我写了如下的SQL语句

select top(10)* from tandor where deptname = '技术部' or compname = '广州分公司'
and id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司')

但是语句中的 id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司')
似乎没有起作用,那么我的分页就没有用了,请问大家应该怎么写。
...全文
57 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
SilverNet 2009-12-07
  • 打赏
  • 举报
回复
谢谢大家!结贴
dawugui 2009-12-07
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 silvernet 的回复:]
谢谢,可以了。

再请问下我如果没有加括号是不是这样执行的
SQL codeselecttop(10)*from tandorwhere (deptname='技术部')or (compname='广州分公司'and idnotin
(selecttop(1) idfrom tandorwhere deptname='技术部'or compname='广州分公司'))
[/Quote]
不加括号,根据逻辑符号的优先顺序来执行.
逻辑运算符的优先顺序
当一个语句中同时包含多个逻辑运算符时,取值的优先顺序依次为:NOT、AND 和 OR。算术(及按位)运算符先于逻辑运算符被处理。

在下例中,高级条件属于心理书籍而不属于商业书籍,因为 AND 优先于 OR:

SELECT title_id, type, advance
FROM pubs.dbo.titles
WHERE type = 'business' OR type = 'psychology'
AND advance > $5500

可以通过添加括号强制首先对 OR 取值的办法来改变查询的含义。以下查询查找所有价格超过 $5,500 的商业书籍和心理书籍:

SELECT title_id, type, advance
FROM titles
WHERE (type = 'business' OR type = 'psychology')
AND advance > $5500

由于存在运算符优先顺序,使用括号(即使不要求)可以提高查询的可读性,并能减少微小错误的发生。使用括号不会造成重大的性能损失。尽管在语法构成上是相同的,但是下例比原例具有更强的可读性:

SELECT title_id, type, advance
FROM pubs.dbo.titles
WHERE type = 'business'
OR (type = 'psychology' AND advance > $5500)

SilverNet 2009-12-07
  • 打赏
  • 举报
回复
谢谢,可以了。

再请问下我如果没有加括号是不是这样执行的

select top(10)* from tandor where (deptname = '技术部') or (compname = '广州分公司'
and id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司'))
dawugui 2009-12-07
  • 打赏
  • 举报
回复
select top 10 * from tandor where (deptname = '技术部' or compname = '广州分公司')
and id not in
(select top 1 id from tandor where deptname = '技术部' or compname = '广州分公司')
ChinaJiaBing 2009-12-07
  • 打赏
  • 举报
回复

--try

select top(10)* from tandor where (deptname = '技术部' or compname = '广州分公司'
)and id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司')



--小F-- 2009-12-07
  • 打赏
  • 举报
回复
--这样呢?
select top(10)* from tandor where (deptname = '技术部' or compname = '广州分公司')
and id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司')
百年树人 2009-12-07
  • 打赏
  • 举报
回复
应该要加个order by吧,否则顺序无法保证

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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