天天看點

資料查詢,簡單查詢及進階查詢

查詢所有列

1.select * from info

查特定列

2.select code,name from info

查出列後加别名,再查姓名

3.select code as '代号',name as '姓名' from info

條件查詢,單條件查詢

4.select * from info where code='p001'

兩個條件,并且的關系

5.select * from info where code='p001' and nation='n001'

範圍查詢

6.select * from car where price between 20 and 50

離散查詢,關鍵字in

7.select * from car where price in(20,30,40)

模糊查詢,使用關鍵字來查,關鍵字like,後面跟字元串

8.select * from car where name like '%奧迪%'

排序,根據某一列,預設的是升序

9.select * from car order by price desc

去重查詢

10.select distinct brand from car

分頁查詢,關鍵字limit,數字分别表示跳過幾條資料,顯示幾條資料

11.select * from car limit 5,5

聚合函數,count代表數量,sum求和   平均  最大值  最小值

12.count()      sum()   avg()   max()   min()

分組查詢,主要用來做統計,根據brand來分

13.select brand,count(*) from car group by brand 

進階查詢

1.連接配接查詢,對結果集列的擴充

select * from info

select * from info,nation   #形成笛卡爾積(連接配接兩張或多張表,資料量小的時候可以用)

select * from info,nation where info.nation=nation.code(用條件來篩選,如果有重複的,一定要先寫表名,沒有重名的就可以直接寫)

select info.code,info.name,sex,nation.name,birthday from info,nation where info.nation=nation.code(篩選出自己想要的資料)

select * from info join nation on info.nation=nation.code(關鍵字join後面加條件,如果隻運作前半句select * from info join的話,和上面的情況一樣,會出現笛卡爾積,和join配合使用的是on,on後面加連接配接條件)

2.聯合查詢,對結果集行的擴充

select code,name from info

union(關鍵字,聯合顯示兩張表,查的列的數量要相同)

select code,name from nation

3.子查詢

父查詢:外層查詢

子查詢:裡層查詢

子查詢的結果做為父查詢的條件

(1)無關子查詢

子查詢在執行的時候和父查詢沒有關系,子查詢可以單獨執行

1.查詢民族為‘漢族’的所有人員資訊

父查詢:select * from info where nation=()

子查詢:select code from nation where name='漢族'

(整合,子查詢的結果當做父查詢的條件)select * from info where nation=(select code from nation where name='漢族')

2.查詢系列名為‘寶馬5系’的所有汽車資訊

select * from car where brand=(select brand_code from brand where brand_name='寶馬5系')

(2)相關子查詢

子查詢在執行的時候和父查詢有關系,子查詢不可以單獨執行

1.查詢汽車表中油耗小于該系列平均油耗的所有汽車資訊

父查詢:select * from car where oil<(該系列平均油耗)

子查詢:select avg(oil) from car where brand=該系列

select * from car as a where oil<(select avg(oil) from car as b where b.brand=a.brand)

繼續閱讀