1. 程式人生 > >mysql 子查詢種類及聯合查詢的sql語句寫法

mysql 子查詢種類及聯合查詢的sql語句寫法

子查詢:

將一個查詢語句巢狀在另一個查詢語句中,內層查詢語句的查詢結果可以作為外層查詢語句提供條件。

1.in ,not in

2.比較運算子>=

select id,name from student where score >=(select level from scholarship where id=1)

3.[not] exists

select  id,username from employee where exists(select id   from department where id=5)

4.any|some  all配合>=比較運算子

select id,name from student where score >=any(select level from scholarship)

5.將查詢結果寫入資料表   保證欄位順序,欄位數目一致test1的列得存在

insert test1(id,num) select id,score from student;

6.建立資料表同時將查詢結果寫入到資料表   如果欄位名稱不一致,以查詢出來的為主,原欄位為null

create table [if not exists] employee(id,score) select id,score from student;

 

聯合查詢:

union去掉重複的 union all簡單並集   兩張表的查詢的列數量一樣,型別可以不一樣

select id from bbs_addr union select name from bbs_brand;  id是BigInt  name是varchar型別