嵌套子查詢

1. 集合成員資格:

eg: 找出選修了ID爲10101的教師所教授的課程段的學生數測試

select count(distinct id)
from takes
where (course_id, sec_id, semester, year) 
    in (select course_id,sec_id, semester, year 
        from teaches 
        where teach.id=10101);

remarks:code

  • 集合跟集合裏面的屬性會一一對應
  • null跟null會被視爲不匹配

2. 集合的比較:

eg: 找出工資至少比biology系某一個教師工資要高的全部教師姓名——用」rem

select name 
from instructor 
where salary > some (select salary 
                     from instructor 
                     where dept_name='biology');

remarks:it

  • =some等價於in
  • >some表示「至少比一個大
  • any跟some用法同樣

eg:找出平均工資最高的系io

select dept_name  
from instructor
group by dept_name
having avg(salary) >= all (select avg(salary)
                            from instructor 
                            group by dept_name);
  • 相似的, >all是「比全部的都大」

3. 空關係測試

  • exist在where的子查詢中做爲參數使用,非空返回true
  • not exists (B except A) 等價於關係A包含關係B,用於測試子查詢結果集中是否不存在元組

4. 重複元組存在測試

eg: 找出全部在2009年最多開設一次的課程select

select T.course_id 
from course as T 
where unique (select R.course_id
                from section as R
                where T.course_id=R.course_id and R.year=2009);
--等價於 
select T.course_id 
from course as T 
where 1>= (select count(R.course_id)
                from section as R
                where T.course_id=R.course_id and R.year=2009);

remarks:方法

  • 若是做爲參數的子查詢結果裏面沒有重複的元組,unique 將返回true
  • 能夠用not exist 測試在一個子查詢的結果中是否存在重複元素

5. from子句中的子查詢

eg: 找出全部系中工資總額最大的系查詢

select max(tot_salary)
from (select dept_name, sum(salary)
        from instructor
        group by dept_name) as dept_total(dept_name, tot_salary);

remarks:集合

  • 哪裏用子查詢的邏輯是:任何select-from-where表達式返回的結果都是關係,於是能夠被插入到select-from-where中任何關係能夠出現的位置
  • 若是想在from嵌套的子查詢裏面用來自from其餘關係的屬性,有的DB裏面支持lateral能夠實現

6. with子句

eg: 查出全部工資總額大於全部系平均工資總額的系di

with dept_total(dept_name, value) as
    (select dept_name, sum(salary)
    from instructor
    group by dept_name),
    dept_total_avg(value) as 
    (select avg(value)
    from dept_total)
select dept_name
from dept_name, dept_total_avg
where dept_total.value>=dept_total_avg.value;

remarks:

  • with子句提供臨時定義關係的方法,只對包含該子句的查詢有效
  • 優勢是邏輯更清晰,還容許在一個查詢內多個地方使用視圖定義

7. 標量子查詢

  • 當子查詢只返回包含單個屬性的單個元組時(即只有一行一列),SQL容許其出如今任何單個表達式能出現的地方,好比select中
相關文章
相關標籤/搜索