约束
举例说明
create table user(
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check ( age>0&&age<=120 )comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '姓名'
)comment '用户表';
insert into user(name,age,status,gender) values('Tome1',18,'1','男'),('Tome2',20,'0','男');
insert into user(name,age,gender) values('Tome4',13,'男');
外键约束
添加外键
crate table 表名 (
字段名 数据类型
constraing [外键名称] froming key(外段字段名) refernces 主表( 主表列名)
)
alter table 表名 add constraing [外键名称] froming key(外段字段名) refernces 主表( 主表列名)
alter table user add constraint fk_user_dept_id foreign key(dept_id) references dept(id);
多表查询
多对多
内连接
隐式内连接
select 字段列表 from 表名 表1,表2.。。 where 条件。。。;
显式内连接
select 字段列表 from 表1 join表2 on 连接条件;
外连接
左外连接
select 字段列表 from 表1 left join 表2 on 条件;
右外连接
select 字段列表 from 表1 righ join 表2 on 条件;
自连接
select 字段列表 from 表a 别名a join 表a 别名b on 条件
联合查询
select 字段列表 from 表a union [all] select 字段列表 from 表b