34,590
社区成员
发帖
与我相关
我的任务
分享
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 '李七','信息部','佛山分公司'
select top(10)* from tandor where deptname = '技术部' or compname = '广州分公司'
and id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司')
逻辑运算符的优先顺序
当一个语句中同时包含多个逻辑运算符时,取值的优先顺序依次为: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)
select top(10)* from tandor where (deptname = '技术部') or (compname = '广州分公司'
and id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司'))
--try
select top(10)* from tandor where (deptname = '技术部' or compname = '广州分公司'
)and id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司')
--这样呢?
select top(10)* from tandor where (deptname = '技术部' or compname = '广州分公司')
and id not in
(select top(1) id from tandor where deptname = '技术部' or compname = '广州分公司')