SQL语句分为三类
- 数据定义语言:简称DDL(Data Definition Language)用来定义数据库对象:数据库DataBase,表table,列column等。关键字:创建create 修改alter 删除drop等
- 数据库操作语言:简称DML(Data Manipulation Language) 用来对数据库中表的记录进行更新。关键字:插入 insert,删除delete 更新 update等
- 数据查询语言:简称DQL(Data Query Language)用来对数据库中表的记录进行查询。关键字:select,from,where等
- 数据控制语言:简称DCL(Data Control Language) 用来定义数据库的访问权限和安全级别及创建用户,关键字 grant等
SQL查询回顾
回顾查询我们使用一个案例:创建一个product商品表
建表语句
create table product (
pid INT PRIMARY KEY auto_increment,
pname varchar(20),
price double,
pdate timestamp
);
- 创建表完毕后,我们可以进行一些查询
查询语法
select [distinct]* | 列名,列名 from 表(where 条件)
简单查询
- 查询所有商品
select * from product
- 查询商品的名称和价格
select pname,price from product;
- 查询所有商品信息使用表别名
select * from product as p;
# 使用别名
select * from product p ;
- 查询商品名 使用列别名
select pname as name from product;
select pname name from product;
- 去掉重复值(按照价格)
select distinct(price) from product;
- 将所有的商品价格加10进行显示
select pname,price+10 from product;
条件查询
- where 后条件写法
-
,<,=,>=,<=,<>(不等于)
- like 使用占位符_和% _代表一个字符 %代表任意个字符
-
select * from product where pname like ‘%新%’;
- in 在某个范围中获得值
select * from product where pid in (2,5,8);
select * from product where pid =1 or pid =2 or pid =3;
- is null 判断是否为空
- 逻辑运算符
- and 多个条件同时成立
- or 多个条件任一成立
- not 不成立
- 查询商品名为“左慈”的商品信息
select * from product where pname = '左慈';
- 查询价格>60的所有的商品的信息
select * from product where price>60;
- 查询商品名称中含有'士'字的商品信息
select * from product where pname like '%士%'
- 查询商品id在(3,6,9)范围内的所有商品信息
select * from product where pid in (3,6,9);
- and 条件使用 查询带有士字的且pid大于4的商品
select * from product where pname like '%士%' and pid >4;
- or 条件使用
select * from product where pid =2 or pid =6;
排序
语法
select * from 表名 order by 字段1 asc|desc 字段2 asc|desc (asc 升序 desc 降序)
order by 必须放到语句的最后面
- 查询所有的商品,按价格进行排序(升序 降序)
select * from product order by price asc;
select * from product order by price desc;
- 查询商品名称中有‘士’字的商品信息,并且按照降序排序
select * from product where pname like '%士%' order by price desc;
聚合
*常用的聚合函数:
* sum() 求和
* avg() 平均
* max() 最大值
* min() 最小值
* count() 计数
聚合函数不统计Null值
- 获得所有商品的价格总和
select sum(price) from product;
- 获得所有商品的平均价格
select avg(price) from product;
- 获得所有商品的个数
select count(*) from product
分组操作 group by
分组后的条件不能再使用where 而要使用having
- 对数据添加分类id
alter table product add civ varchar(32);
- 初始化数据
update product set cid = '1'
update product set cid='2' where pid in (5,6,7)
- 根据cid字段分组,分组后统计商品的个数
select cid,count(*) from product group by cid;
- 根据cid分组,分组统计每组商品的平均价格,并且平均价格大于20000元
select avg(price) from product group by cid having avg(price)>20000
limit分页
- limit x,y
* x:代表要查询的页数(起始位置) 计算:要查询的页数-1*每页要显示的数目就是值
* y:代表每页显示的数目
select * from product limit 6,3 每页显示3条记录要查询第三页
网友评论