MySQL之DQL操作
1.什么是DQL操作?
DQL是指数据查询语言,全称Data Query Language,用来查询数据库中表的记录。关键字:select,from,where等。
2.准备动作:建表
为了更好的解释DQL操作,先来建一张表并写入一些数据,方便下面举栗子。
- 建表
create table product(
pid int primary key auto_increment, //设置主键自增
pname varchar(20),
price double,
pdate timestamp
);
- 插入数据
insert into product values (null,'詹姆斯',4000,current_time()); //current_time()表示获取当前时间戳
insert into product values (null,'鲍尔',750,current_time());
insert into product values (null,'莺歌拉姆',576,current_time());
insert into product values (null,'隆指导',900,current_time());
insert into product values (null,'麦基',239,current_time());
insert into product values (null,'库兹马',169,current_time());
insert into product values (null,'哈特',166,current_time());
3.查询:select
select [distinct] *|列名,from 表 [where 条件];
简单查询
select * from 表名; //查询表中所有字段
select 字段1,字段2,... from 表名 //查询表中指定字段
select * from 表名 as 别名; //表别名查询
select 字段名 as 别名 from 表名; //字段别名查询
select distinct 字段 from 表名; //去掉指定字段重复值
例如
条件查询
select * from 表名 where 条件
where后条件写法:
-
,=,<,>=,<=,<>(不等于)
- like使用占位符“_”和“%”,_代表一个字符,%代表任意个字符。
- in在某个范围内获取值
- and,or等逻辑表达式
例如:
排序
select .. order by 字段1 asc|desc,字段2asc|desc...
其中asc表示升序,desc表示降序,不写默认是升序排列
栗子:
聚合
常用的聚合函数有:sum()求和,avg()平均,max()最大值,min()最小值,count()计数。。
注意:聚合不统计null值
栗子:
分组
一些准备工作
分组查找