子查詢是將乙個查詢語句巢狀在另乙個查詢語句中。內層查詢語句的查詢結果,可以作為外層查詢語句提供條件。
insert
[into
] tbl_name [
(col_name,..
.)]select..
.
create
table[if
notexists
] tbl_name
[(create_definition,..
.)]select_statement
**示例:
-- 由[not] in引發的子查詢
select username,depid from employee where depid in
(select id from department)
;select username,depid from employee where depid notin(
select id from department)
;-- 建立學員表student
-- id username score
create
table
ifnot
exists student
( id tinyint
unsigned
auto_increment
key,
username varchar(20
)not
null
unique
, score tinyint
unsigned);
insert student(username, score)
values
('king',95
),('king1',35
),('king2',45
),('king3',55
),('king4',65
),('king5',75
),('king6',80
),('king7',90
),('king8',25
);-- 建立獎學金scholarship
-- id ,level
create
table
ifnot
exists scholarship
( id tinyint
unsigned
auto_increment
key,
level
tinyint
unsigned);
insert scholarship(
level
)values(90
),(80
),(70
);select
*from scholarship;
select
*from student;
-- 查詢獲得1等獎學金的學員有
select username
from student
where score >=
(select
level
from scholarship where scholarship.id =1)
;-- 查詢部門表中
select
*from department
where id =4;
select id, username
from employee
where
exists
(select
*from department where id =3)
;-- 查詢所有獲得獎學金的學員
select id, username, score
from student
where score >=
any(
select
level
from scholarship)
;select id, username, score
from student
where score >=
some
(select
level
from scholarship)
;-- 查詢所有學員中獲得一等獎學金的學員
select id, username, score
from student
where score >=
all(
select
level
from scholarship)
;-- 查詢學員表中沒有獲得獎學金的學員
select id, username, score
from student
where score <
all(
select
level
from scholarship)
;select id, username, score
from student
where score <
any(
select
level
from scholarship)
;select id, username, score
from student
where score <=
any(
select
level
from scholarship)
;-- 相當於in
select id, username, score
from student
where score =
any(
select
level
from scholarship)
;select id, username, score
from student
where score in
(select
level
from scholarship)
;-- 相當於not in
select id, username, score
from student
where score notin(
select
level
from scholarship)
;select id, username, score
from student
where score <>
all(
select
level
from scholarship)
;
MySQl學習筆記(子查詢)
修改資料表 新增單列 alter table tbl name add column col name column definition first after col name 省略first after col name將預設你所新增的列位於所有列的最後面 例 alter table user...
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...
(MySQL筆記)MySQL子查詢
mysql的select語句中支援子查詢。子查詢是將乙個select語句的查詢結果作為中間結果,供另乙個select語句查詢呼叫,子查詢也叫做子選擇或者巢狀選擇。如 select studentno from select studentno,from student where age 18 as...