ORACLE學習 5 子查詢

2021-09-24 20:26:39 字數 2903 閱讀 8141

1、子查詢簡介

1.1 子查詢語法:

select	select_list

from table

where expr operator

(select select_list

from table);

1.2 注意:

a.子查詢要包含在括號內;

b.將子查詢放在比較條件的右側;

c.單行操作對應單行子查詢,多行操作對應多行子查詢;

2、單行子查詢

單行子查詢只返回一行,單行比較操作符有:

單行子查詢操作符

操作符含義=

等於》大於》=

大於等於

<

小於<=

小於等於

<>

不等於 例如:

返回job_id與141號員工相同,salary比143號員工多的員工姓名,job_id 和工資

select

last_name, job_id, salary

from

employees

where job_id =

(select

job_id

from

employees

where employee_id =

141)

and salary >

(select

salary

from

employees

where employee_id =

143);

2.1 在子查詢中使用子函式

例如:返回公司工資最少的員工的last_name,job_id和salary

select

last_name, job_id, salary

from

employees

where salary =

(select

min(salary)

from employees);

#多行子查詢使用單行比較符

select

employee_id, last_name

from

employees

where salary =

(select

min(salary)

from

employees

group

bydepartment_id);

error at line 4:

ora-

01427: single

-row subquery returns more thanone row

子查詢中的空值問題:

select

last_name, job_id

from

employees

where job_id =

(select

job_id

from

employees

where last_name =

'haas

');

3.多行子查詢

多行子查詢返回多行,應該使用多行比較操作符

操作符含義

in等於列表中的任意乙個

any和子查詢返回的某乙個值比較

all和子查詢返回的所有值比較

3.1在子查詢中使用any操作符

--

返回其它部門中比job_id為『it_prog』部門任一工資低的員工的員工號、姓名、job_id 以及salary

select

employee_id, last_name, job_id, salary

from

employees

where salary <

any(

select

salary

from

employees

where job_id =

'it_prog')

and job_id <>

'it_prog

';

3.2在子查詢中使用all操作符

--

返回其它部門中比job_id為『it_prog』部門所有工資都低的員工的員工號、姓名、job_id 以及salary

select

employee_id, last_name, job_id, salary

from

employees

where salary <

all(

select

salary

from

employees

where job_id =

'it_prog')

and job_id <>

'it_prog

';

3.3子查詢中的控制問題

select

emp.last_name

from

employees emp

where emp.employee_id notin(

select

mgr.manager_id

from

employees mgr);

--no rows selected

MySQL學習筆記(5)子查詢

測試子查詢 測試由in引發的子查詢 select from emp where depid in select id from dep select from emp where depid not in select id from dep 由exists 引發的子查詢 select from e...

Oracle的查詢 子查詢

子查詢 子查詢返回乙個值 查詢出工資和scott一樣的員工資訊 select from emp where sal in select sal from emp where ename scott 子查詢返回乙個集合 查詢出工資和10號部門任意員工一樣的員工資訊 select from emp wh...

Oracle學習筆記 with as子查詢用法

with as短語,也叫做子查詢部分 subquery factoring 可以定義乙個sql片斷,該sql片斷會被整個sql語句用到。該語句會在真正的查詢之前預先構造乙個臨時表,之後可以多次使用做進一步的分析和處理。優勢 1.可以使sql語句的可讀性更高 2.一次分析,多次使用,提高效能 語法 w...