关键字
1、排序;
order by desc(降序)/asc(升序默认的)
#在 student表中 根据id进行降序排列
select * from student order by id desc;
# 如果student表中id相同则根据score降序排列
select * from student order by id asc,score desc;
2、运算符
判断:=
非等:<>
…>,<,!=,<=,>=
3、连接符
and 且关系(前后两个条件必须满足)
or 或关系(两者满足其中一个)
# 删除部门编号为空的数据
delete from emp where dno is null;
4、in/not in
# 需求:查询指定部门的员工信息
select * from emp where dno in(10,11,12,20,30,31,55,66,77);
5、分组(group by)
根据数据中的某一个特征对数据进行划分,这种形式叫分组
# 需求:求男生女生人数在3个以上的员工信息
select sex,count(sex) from emp group by sex having count(sex)>3;
6、having和where有什么区别
1.where是直接跟在表的后面的条件,having是跟在group by后面的条件
2.having的使用需要结合group by,group by在进行分组的时候是很耗性能的
7、别名
别名仅仅只是在当前要显示的结果中生效,起到简化及通俗易懂的效果
关键词:as
# 需求:显示员工的信息(as可以省略不写)
select eno as 员工编号,ename as 员工姓名,dno 部门编号 from emp;
8、分页(limit)
数据库下标是从0开始
# 需求:查询前三条数据
select * from emp limit 0,3;
# 需求:查询第二页的数
select * from emp limit 3,3;
约束
约束就是给字段添加对应的规则,用户在进行数据的操作时必须要符合对应的规则,才能进行操作,可以有效的保证数据的安全性
约束名 | 关键字 | 描述 |
---|---|---|
非空约束 | not null | 数据不能为空 |
唯一约束 | unique | 数据不能重复 |
主键 | primary key | 主键(非空且唯一) |
外键 | foreign key | 外键(用于表之间的关联关系) |
# 指定手机号不能为空
alter table emp modify phone varchar(11) not null;
# 指定手机号是唯一的(null值是可以重复的)
alter table emp modify phone varchar(11) unique;
# 指定手机号不能为null且唯一
alter table emp modify phone varchar(11) not null unique;`
# 指定员工编号为主键
alter table emp modify eno int primary key;
自增长(auto_increment)
# 让员工编号自增长
alter table emp modify eno int auto_increment;
外键约束
# 给员工表中的部门编号设置外键约束
alter table 表名 add constraint 约束名 foreign key(当前表中约束的字段) references 主表表名(要约束的字段名);
alter table emp add constraint fk_emp_dno foreign key(dno) references depart(dno);
1.主表中作为外键使用的字段要求一定是非空且唯一的
2.如果此时要删除主表中的数据,前提是该外键字段的值在从表中没有被使用
创建表时添加约束:
create table salarys(
sid int primary key auto_increment,
salary double(8,2) not null,
eno int not null,
constraint fk_salarys_eno foreign key(eno) references emp(eno));