標籤:sql 多個 關鍵字 val count 條件 rom nas 外鍵
老師提綱
1. create database test
2. drop database test
3. create table info
(
code int primary key,
name varchar(20) not null
)
auto_increment 自增長列
foreign key(列名) references 主表名(列名) 外鍵關係
4. drop table info
CRUD:
1.insert into 表名(列名) values(值)
2.delete from 表名 where 條件
3.update 表名 set 列名=值 where 條件
簡單查詢
1.最簡單查詢(查所有資料)
select * from 表名; 註:* 代表所有列
select * from info
2.查詢指定列
select code,name from info
3.修改結果集的列名
select code as ‘代號‘,name as ‘姓名‘ from info
4.條件查詢
select * from info where code=‘p003‘
5.多條件查詢
查詢info表中code為p003或者nation為n001的所有資料
select * from info where code=‘p003‘ or nation=‘n001‘
查詢info表中code為p004並且nation為n001的資料
select * from info where code=‘p004‘ and nation=‘n001‘
6.範圍查詢
select * from car where price>=40 and price<=60
select * from car where price between 40 and 60
7.離散查詢
查詢汽車價格在(10,20,30,40,50,60)中出現的汽車資訊
select * from car where price=10 or price=20 or price=30 or price=40 or price=50 or price=60
select * from car where price in(10,20,30,40,50,60)
select * from car where price not in(10,20,30,40,50,60)
8.模糊查詢(關鍵字查詢)
查詢car表裡面名稱包含奧迪的
select * from car where name like ‘%奧迪%‘ %任意n個字元
查詢car中名稱第二個字元為‘馬’的汽車
select * from car where name like ‘_馬%‘ _任意一個字元
9.排序查詢
select * from car order by price asc asc升序(省略)
select * from car order by oil desc desc降序
先按照brand升序排,再按照price降序排
select * from car order by brand,price desc
10.去重查詢
select distinct brand from car
11.分頁查詢
一頁顯示10條 當前是第3頁
select * from chinastates limit 20,10
一頁顯示m條 當前是第n頁
limit (n-1)*m,m
12.彙總函式(統計函數)
select count(areacode) from chinastates #查詢資料總條數
select sum(price) from car #求和
select avg(price) from car #求平均
select max(price) from car #求最大值
select min(price) from car #求最小值
13.分組查詢
查詢汽車表中每個系列下有多少個汽車
select brand,count(*) from car group by brand
查詢汽車表中賣的汽車數量大於3的系列
select brand from car group by brand having count(*)>3
自己筆記
簡單查詢
select * from 表名; 注意:*代表所有
);
查詢指定列
select 列名,列名 from 表名
修改結果集的列名
select 列名 as‘‘,列名 as‘‘ from 表名
條件查詢
select * from 表名 where 條件
多條件查詢
select * from 表名 where 條件 or 條件
select * from 表名 where 條件 and 條件
範圍查詢
select * from 表名 where price>=40 and price<=60;
select * from 表名 where price betwen 40 and 60
離散查詢
select * from 表名 where price in(20,30,40,50);
select * from 表名 where price not in(20,30,40,50)
模糊查詢(關鍵字查詢)
select * from 表名 where name like ‘%奧迪%‘ %代表任意多個字元
select * from 表名 where name like ‘_馬%‘ _代表任意一個字元
9.排序查詢
select * from car order by price asc asc升序(省略)
select * from car order by oil desc desc降序
先按照brand升序排,再按照price降序排
select * from car order by brand,price desc
去重查詢
select distinct 列 from 表名
分頁查詢
一頁顯示10條,當前是第二頁
select *from 表名 limit 10(跳過多少條),10(取第三條)
彙總函式(統計函數)
select count (主鍵) from 表名 查詢資料總條數
select sum (列名) from 表名 求和
select avg(列名) from 表名 求平均
select max(列名) from 表名 求最大值
select min (列名) from 表名 求最小值
分組查詢
查詢汽車表中每個系列下有多少個汽車
select brand,count (*) from car group by brand
查詢汽車表中所買的數量大於3的系列
select brand from car group by brand having count*
12-2 mySQL 查詢