七、字段约束
1、主键约束
作用:记录的唯一标识
特点:唯一、不能为空
案例:
CREATE TABLE student (
id int auto_increment, #原则
name varchar(50),
PRIMARY KEY ( id ) #主键约束
)

2、非空约束
特点:不能为空
案例:
CREATE TABLE student (
id int auto_increment,
name varchar(50) not null, #非空约束
phone varchar(11),
PRIMARY KEY (id)
)

3、唯一约束
特点:唯一
案例:
CREATE TABLE student (
id int auto_increment,
name varchar(50) not null,
phone varchar(11) unique, #唯一约束
PRIMARY KEY (id)
)

4、默认约束
特点:填充默认值
案例:
CREATE TABLE student (
id int auto_increment,
name varchar(50) not null,
phone varchar(11) unique,
sex bit default 0,
hobby varchar(100) default '无', #默认约束
PRIMARY KEY (id)
)

5、外键约束
作用:建立表之间的关联联系时,保障数据完整性。
特点:另一张表的主键(也可是唯一约束列)
案例:
create table tb_class(
id int(11) auto_increment, -- id是主键列,不用显示插入值 让其自动增长
class_name varchar(30) not null, -- not null 非空约束
class_desc varchar(100), -- 班级描述
primary key (id) -- 为tb_class表的id列设置主键约束
)ENGINE=INNODB,DEFAULT CHARSET UTF8;
CREATE TABLE student (
id int auto_increment,
name varchar(50) not null,
phone varchar(11) unique,
sex bit default 0,
hobby varchar(100) default '无',
class_id int,
PRIMARY KEY (id),
foreign key (class_id) references tb_class(id) #外键约束
)
八、表关系
一对一:
学生表(tb_student):
id
name
cid #外键
班级表(tb_class):
id
name
一对多:
班级表(tb_class):
id
name
学生表(tb_student):
id
name
cid #外键
多对多:
学生表(tb_student):
id
name
课程表(tb_course):
id
name
中间表/关联表(tb_student_course):
sid
cid
九、单表查询
1、简单查询
select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp
select empno,ename,job from emp
select * from emp
#使用别名
select empno as no, ename name from emp
select e.empno,e.ename from emp e
select e.empno as no, e.ename name from emp e
select e.* from emp e
select e.*,d.dname from emp e, dept d
#使用算术表达式
select ename,sal,sal*0.8 from emp
select ename,sal,sal*1.2 from emp
select ename,sal,sal*12+1000 from emp
#去重查询
select distinct deptno from emp
select distinct job from emp
select distinct deptno,job from emp
#排序查询
select * from emp order by sal desc; #降序
select * from emp order by sal; #升序
select * from emp order by sal asc; #升序

2、分页查询
语法:
select 字段名... from 表名 limit index,pageSize
案例:
#每页5条,查询第1页
select * from emp limit 0,5
select * from emp limit 5
#每页5条,查询第2页
select * from emp limit 5,5
#查询工资最高的前3名员工
select * from emp order by sal desc limit 0,3
#查询2号部门工资最高的前3条员工
select * from emp where deptno=2
select * from emp where deptno=2 order by sal desc limit 0,3

3、合并查询
作用:将两个select的查询结果合并为一个
关键字:
union all:合并
union:合并,去重
案例:
#查询2号部门员工的job
select job from emp where deptno=2;
#查询3号部门员工的job
select job from emp where deptno=3;
#查询2号部门员工的job union all 查询3号部门员工的job
select job from emp where deptno=2
union all
select job from emp where deptno=3
select job from emp where deptno=2
union all
select job,ename from emp where deptno=3 #报错
#查询2号部门员工的job union 查询3号部门员工的job
select job from emp where deptno=2 #5条
union
select job from emp where deptno=3 #6条

10万+

被折叠的 条评论
为什么被折叠?



