close
文章出處

查詢所有列
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)




不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    AutoPoster 發表在 痞客邦 留言(0) 人氣()