MySQL學習筆記(5)子查詢

2021-09-29 15:37:23 字數 2534 閱讀 7264

-- 測試子查詢

-- 測試由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 emp where exists (select depname from dep where id=10);

select * from emp where not exists (select depname from dep where id=1);

-- 學員stu

create table stu(

id tinyint unsigned auto_increment key,

username varchar(20) not null unique,

score tinyint unsigned not null

);insert stu(username,score) values('king',95),

('queen',75),

('zhangsan',69),

('lisi',78),

('wangwu',87),

('zhaoliu',88),

('tianqi',98),

('ceshi',99),

('tiancai',50);

-- 分數級別level

create table level(

id tinyint unsigned auto_increment key,

score tinyint unsigned comment '分數'

);insert level(score) values(90),(80),(70);

-- 查詢出成績優秀的學員

select score from level where id=1;

select id,username,score from stu

where score>=(select score from level where id=1);

-- 查詢出沒有得到評級的學員

select id,username,score from stu

where score<(select score from level where id=3);

-- 帶有any some all關鍵字的子查詢

select * from stu

where score>= any(select score from level);

select * from stu

where score>= some(select score from level);

select * from stu

where score>= all(select score from level);

select * from stu

where score< all(select score from level);

select * from stu

where score=any(select score from level);

select * from stu

where score!=all(select score from level);

-- 建立乙個user1表,id username

create table user1(

id int unsigned auto_increment key,

username varchar(20)

)select id,username from emp;

-- 將stu表中id=3的使用者名稱寫入到user1表中

insert user1(username) select username from stu where id=3;

-- 建立象user1一樣的表user2

create table user2 like user1;

insert user2(username) select username from stu;

-- 將stu表中的tiancai使用者名稱新增到user2表中

insert user2 set username=(select username from stu where id=5);

-- 去掉欄位的重複值

select distinct(username) from user2;

-- 將user1和user2資料合併到一起

--去重

select username from user1

union

select username from user2;

--不去重

select username from user1

union all

select username from user2;

MySQl學習筆記(子查詢)

修改資料表 新增單列 alter table tbl name add column col name column definition first after col name 省略first after col name將預設你所新增的列位於所有列的最後面 例 alter table user...

MySQL學習筆記 子查詢

子查詢是將乙個查詢語句巢狀在另乙個查詢語句中。內層查詢語句的查詢結果,可以作為外層查詢語句提供條件。insert into tbl name col name,select.create table if notexists tbl name create definition,select sta...

(MySQL筆記)MySQL子查詢

mysql的select語句中支援子查詢。子查詢是將乙個select語句的查詢結果作為中間結果,供另乙個select語句查詢呼叫,子查詢也叫做子選擇或者巢狀選擇。如 select studentno from select studentno,from student where age 18 as...