1. 程式人生 > >數據庫基礎查詢方法

數據庫基礎查詢方法

avg -1 指定 字段排序 sum 分組查詢 最小值 group by nat

mysql表格查詢方法:

查詢:

1.簡單查詢

select * from Info --查所有數據
select Code,Name from Info --查指定列的數據
select Code as ‘代號‘,Name as ‘姓名‘ from Info --給列指定別名

2.條件查詢

select * from Info where Code=‘p001‘
select * from Info where Sex=‘true‘ and Nation=‘n001‘ --多條件並的關系
select * from Info where Sex=‘true‘ or Nation=‘n001‘ --多條件或的關系

3.範圍查詢

select * from Car where Price>40 and Price<50
select * from Car where Price between 40 and 50

4.離散查詢

select * from Car where Code in (‘c001‘,‘c005‘,‘c010‘,‘c015‘)
select * from Car where Code not in (‘c001‘,‘c005‘,‘c010‘,‘c015‘)

5.模糊查詢

select * from Car where Name like ‘%寶馬%‘ --查包含寶馬的
select * from Car where Name like ‘寶馬%‘ --查以寶馬開頭的
select * from Car where Name like ‘%寶馬‘ --查以寶馬結尾的
select * from Car where Name like ‘寶馬‘ --查等於寶馬的

select * from Car where Name like ‘__E%‘ --查第三個字符是E的

% 代表是任意多個字符

_ 代表是一個字符

6.排序查詢

select * from Car order by Price asc --以價格升序排列
select * from Car order by Price desc --以價格降序排列
select * from Car order by Oil desc,Price asc --以兩個字段排序,前面的是主條件後面的是次要條件

7.分頁查詢

select top 5 * from Car
select top 5 * from Car where Code not in (select top 5 Code from Car)

當前頁:page = 2; 每頁顯示:row = 10;

select top row * from Car where Code not in (select top (page-1)*row Code from Car)

8.去重查詢

select distinct Brand from Car

9.分組查詢

select Brand from Car group by Brand having count(*)>2

10.聚合函數(統計查詢)

select count(*) from Car --查詢所有數據條數
select count(Code) from Car --查詢所有數據條數

select sum(Price) from Car --求和
select avg(Price) from Car --求平均
select max(Price) from Car --求最大值
select min(Price) from Car --求最小值


高級查詢

1.連接查詢

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 on 的形式

2.聯合查詢

select Code,Name from Info
union
select Code,Name from Nation

3.子查詢

一條SQL語句中包含兩個查詢,其中一個是父查詢(外層查詢),另一個是子查詢(裏層查詢),子查詢查詢的結果作為父查詢的條件。

--查詢民族為漢族的所有人員信息
select * from Info where Nation = (select Code from Nation where Name = ‘漢族‘)


(1)無關子查詢

子查詢可以單獨執行,子查詢和父查詢沒有一定的關系

--查詢系列是寶馬5系的所有汽車信息
select * from Car where Brand =(select Brand_Code from Brand where Brand_Name = ‘寶馬5系‘)


(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)

數據庫基礎查詢方法