DQL 数据库查询
关键词 select
注意: 从数据库查询信息不会改变数据库表中的数据
查询会产生一张新的表(虚拟表) 从原表中查出来的
查询表中所有字段内容(* 代表所有字段)
select * from 表名;
查询表中 A 和 B 字段
select A, B from 表名;
1.关系运算符 = != < > <= >= <>不等于
2.between...and... 范围查询
3.is not null 判断不是空
is null 判断是空
4.逻辑运算符
and 、 && 与
or 、 || 或
not 、 ! 非
5.int(set) 在什么范围之内 用逗号隔开
not in
字段控制语句
1.去除重复数据 distinct
select distinct 字段 from 表名;
2.查看两个字段之和(求和)
select 字段1 + 字段2 from 表名;
如果有空值 给null赋值0
select 字段1 + ifnull (字段2,0) from 表名;
查询时可以使用as关键词给字段起别名 as可以省略
select 字段1 + ifnull (字段2,0) total from 表名;
3.排序 order by 字段 --- 按该字段排序
默认是升序(ASC)
降序(DESC)
ensample: 给stu表 按年龄排序
select * from stu order by age;
4.模糊查询 like
% 表示多个字符 0~n
_ 表示单个字符
ensample: 查询emp表中名字中带l的所有人的信息
select * from emp where ename like '%l%';
5.聚合函数 count 、sum
聚合函数都可以自动过滤空值
COUNT 查询的是 一共有多少条记录 获取总记录数
select count(*) from 表名;
ensample: 查询公司sal的总和(查询时 字段的记录数要相同)
select count(*) , sum(sal) from 表名;
ensample: 统计月薪sal与佣金comm之和大于8500元的人数
select count(*) from 表名 where sal+ifnull(comm,0) > 8500;
ensample: 查询最高工资和最低工资
select max(sal),min(sal) from 表名;
6.分组查询 group by
ensample: 查询每个部门deptno的部门编号和每个部门的工资和
select deptno,sum(sal) from 表名 group by deptno;
ensample: 查询每个部门的部门编号以及每个部门工资大于1500的人数:
先筛选大于1500的 再分组
select deptno ,count(*) from 表名 sal>1500 group by deptno;
ensample: 查询工资总和大于9000的部门编号以及工资和
HAVING是分组以后使用的筛选关键词
HAVING后面可以跟聚合函数
select deptno , sum(sal) from 表名 group by deptno having sum(sal)>9000;
ensample: 统计所有员工平均工资
select avg(sal+ifnull(comm,0)) from 表名;
7.分页查询 limit
ensample: 查询前三条数据
参数1 从哪条数据开始
参数2 查询几条
select * from 表名 limit 0,3;
数据完整性
1.实体完整性
主键约束 primary key
主键特点: 唯一 且 不能为null 一般每张表 都设一个主键
ensample: 创建一个表stu1 sid sname 把id设置为主键
方式一:
create table stu1 (
sid int primary key,
sname varchar(20)
);
方式二:
create table stu1 (
sid int ,
sname varchar(20),
primary key (sid)
);
可以用来创建联合主键
联合主键中的字段值完全一样才算重复
create table stu2 (
classid int,
sid int ,
sname varchar(20),
primary key (sid ,classid)
);
方式三:
可以用来为已经创建好的表添加主键
create table stu1(
sid int,
sname varchar(20)
);
添加主键约束
alter table stu1 add constraint primary key(sid);
删除约束主键
alter table stu1 drop primary key;
唯一约束 unique
特点: 值唯一(可以为空)
create table stu3 (
sid int primary key,
sname varchar(20) unique
);
insert into stu3 (sname,sid) values('haha',null);2.域完整性
限制此单元格内的数据正确
auto_increment 自动增加数据
default 默认数值
not null 不能为空
create table stu4(
sid int primary key auto_increment,
sname varchar(20) not null,
sgender varchar(20) default '男'
)
3.引用完整性
引用约束(参照物约束): 主表和从表有依赖关系 从表依赖主表 这时可以给从表添加一个约束 外键约束
外键约束 foreign key(sid)
ensample: 建立学生表和学生成绩表 引用约束创建联系
create table student (
sid int primary key,
sname varchar(20)
);
create table score (
sid int,
score int,
constraint fk_stu_sco_sid foreign key(sid) references student(sid)
);
外键约束的第二种创建方式:
create table student(
sid int primary key,
sname varchar(20)
);
create table score(
sid int,
score int
);
给score表添加外键alter table score add constraint fk_stu_sco foreign key(sid)
REFERENCES student(sid);
删除(要使用约束的别名来删除)
一个表可以有多个外键 需要使用约束名字
注意: 约束名(外键名字)不能重复
alter table score drop foreign key fk_stu_sco;