sql server中如何用同一句语句实现查询所有条件或查询某一条件

如题所述

嵌套SELECT语句也叫子查询,一个 SELECT 语句的查询结果能够作为另一个语句的输入值。子查询不但能够出现在Where子句中,也能够出现在from子句中,作为一个临时表使用,也能够出现在select list中,作为一个字段值来返回。
1、单行子查询 :单行子查询是指子查询的返回结果只有一行数据。当主查询语句的条件语句中引用子查询结果时可用单行比较符号(=, >, <, >=, <=, <>)来进行比较。 例:
select ename,deptno,sal from emp
where deptno=(select deptno from dept where loc='NEW YORK');

2、多行子查询:多行子查询即是子查询的返回结果是多行数据。当主查询语句的条件语句中引用子查询结果时必须用多行比较符号(IN,ALL,ANY)来进行比较。其中,IN的含义是匹配子查询结果中的任一个值即可("IN" 操作符,能够测试某个值是否在一个列表中),ALL则必须要符合子查询的所有值才可,ANY要符合子查询结果的任何一个值即可。而且须注意ALL 和ANY 操作符不能单独使用,而只能与单行比较符(=、>、< 、>= 、<= 、<>)结合使用。 例:
1).多行子查询使用IN操作符号例子:
查询选修了老师名叫Rona(假设唯一)的学生名字
sql> select stName from Student
where stId in(selectdistinct stId from score where teId=(select teId from teacher where teName='Rona'));
查询所有部门编号为A的资料: SELECT ename,job,sal FROM EMP
WHERE deptno in ( SELECT deptno FROM dept WHERE dname LIKE 'A%');

2).多行子查询使用ALL操作符号例子:查询有一门以上的成绩高于Kaka的最高成绩的学生的名字: sql> select stName from Student
where stId in(select distinct stId from score where score >all(select score from score where stId=(select stId from Student where stName= 'Kaka') )); 3). 多行子查询使用ANY操作符号例子:查询有一门以上的成绩高于Kaka的任何一门成绩的学生的名字:
sql> select stName from Student
where stId in(select distinct stId from score where score >any(select score from score where stId=(select stId from Student where stName='Kaka')));

希望能帮到你
温馨提示:答案为网友推荐,仅供参考