1.簡單查詢
select * from info;
select Code as '代號',name as '姓名' from info;
2.條件查詢
select * from car where code = 'c002';
select * from car where brand ='b001' and power = 130; #或用or
3.模糊查詢
select * from car where name like '%奧迪%'; %代表任意多個字符包括0個 _代表一個字符
4.排序查詢
select * from car order by brand, powers desc; asc升序默認可以不寫
5。范圍查詢
select * from car where price between 40 and 60;
6.離散查詢
select * from car where code in('coo1','c003','c005','c007');
select * from car where code not in('coo1','c003','c005','c007');
7.統計查詢(聚合函數)
select count(code) from car; 查詢數據條數也可以count(*)這么寫,性能低
select sum(price) from car; 求和
select max(code) from car; 最大
select min(brand) from car; 最小
select avg(price) from car; 平均
select year(brithday) from dtudent; # 取出生年月的年
8.分頁查詢
select * from Car limit (n-1)*5,5 #第n頁,每頁顯示五條數據
9.去重查詢
select distinct Brand from Car
10.分組查詢
select brand,count(*),Brand from Car group by Brand #把brand列的相同值組合起來,並這一條數據對該列或或其他列進行操作例如求平均值
select Brand from Car group by Brand having count(*)>3 #分組之后根據條件查詢使用having 不使用where
高級查詢
1.連接查詢,對列的擴展
select * from Info,Nation #形成笛卡爾積
select Info.Code,Info.Name,Info.Sex,Nation.Name,Info.Birthday from Info,Nation where Info.Nation = Nation.Code
select * from Info join Nation
select * from Info join Nation on Info.Nation = Nation.Code
2.聯合查詢,對行的擴展
select Code,Name from Info
union
select Code,Name from Nation
3.子查詢
(1)無關子查詢
外層查詢 (里層查詢)
子查詢的結果當做父查詢的條件
子查詢:select Code from Nation where Name='漢族'
父查詢:select * from Info where Nation = ''
select * from Info where Nation = (select Code from Nation where Name='漢族')
(2)相關子查詢
查詢汽車表中油耗低於該系列平均油耗的所有汽車信息
父查詢:select * from Car where Oil<(該系列平均油耗)
子查詢:select avg(Oil) from Car where Brand = '某個系列'
select * from Car a where Oil<(select avg(Oil) from Car b where b.Brand = a.Brand )