sql怎么用查詢結果作為條件進行查詢
嵌套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'))); 希望能幫到你。
轉載請注明出處華閱文章網 » sql把查詢語句當條件