等值条件连接
等值条件连接,左表的某一列和右表的某一列的列值相等的情况时进行连接
select a.,b.
from 左表 as a, 右表 as b
where a.连接列名=b.连接表名
【注意】若n个表相连接时,必须有n-1个等值连接条件
join内连接
语法:
select 字段列表
from 表1 【as 别名】
join 表2 【as 别名】 on (表1.字段=表2.字段)
[where 语句]
[order by [表明.] 语句]
[limit offset ,size]
[group by 字段]
[having 聚合函数条件语句]
例: select a.,b.
from tb_emp a join tb_dept b on a.dept_id=b.id;
join外连接
外连接:除了满足连接条件的数据之外,将左表或者右表的其余数据显示出来。
左外连接 left join 将左边数据全部显示出来
右外连接 right join 将右表的数据全部列出
约束管理
主键约束
create table tb_task(
id int primary key auto_increment,
title varchar(200) comment '任务描述',
from_emp_id int comment '下单人员的id',
to_emp_id int comment '接单人员的id',
create_time timestamp comment '下单时间',
last_time timestamp comment '结单时间'
);
insert into tb_task(title, from_emp_id, to_emp_id, create_time, last_time) values
('涨薪申请100万', 1, 20, '2012-10-12 10:15:12', '2012-10-20 09:10:10'),
('内购两台云服务器32核128G内存', 7, 20, '2012-10-21 00:00:00', '2012-10-21 12:15:00');
-- 删除tb_task表的主键约束
alter table tb_task modify id int;
alter table tb_task drop primary key;
-- 插入任务单号为1的信息
insert into tb_task values
(1, '涨薪申请50万', 2, 20, '2012-10-13 10:15:12', '2012-10-20 10:10:10');
-- 增加tb_task 主键约束
alter table tb_task modify id int primary key auto_increment;
-- 插入任务记录
insert into tb_task(title, from_emp_id, to_emp_id, create_time, last_time) values
('涨薪申请30万', 1, 20, '2012-10-12 10:15:12', '2012-10-20 09:10:10'),
('内购两台云服务器32核128G内存', 7, 20, '2012-10-21 00:00:00', '2012-10-21 12:15:00');
外键约束
添加语法:
创建表时:
- 列名 列的类型 references 主表(主表的主键字段)
- ,constraint 约束名 foreign key (外键字段) references 主表(主表的主键字段)
已存在表:
alter table 表名
add constraint 约束名 foreign key (外键字段) references 主表(主表的主键字段)
级联语句:
on delete cascade 当主表的数据删除时,外键所在的记录也会删除
on delete set null 当主表的数据删除时,外键所在的记录则会设置为Null
on update cascade 当主表的数据更新时,外键所在的记录则会更新
-- 增加工单表的人员字段外键约束
alter table tb_task
add constraint task_emp_fk1 foreign key (from_emp_id) references tb_emp(id);
alter table tb_task
add constraint task_emp_fk2 foreign key (to_emp_id) references tb_emp(id);
删除约束
alter table 表名 drop 约束类型 [约束名]
-- 删除tb_emp 的emp_dept_fk 的外键约束
alter table tb_emp drop foreign key emp_dept_fk;
-- 增加tb_emp 的emp_dept_fk 的外键约束,且级联更新(on update cascade)
alter table tb_emp add constraint emp_dept_fk
foreign key (dept_id) references tb_dept(id) on update cascade;
查询约束
use information_schema 进入这个字典数据库中
select constraint_name,table_schema,table_name,constraint_type from table_constraints where table_schema=‘pdb’; 查看约束类型
elect table_name,engine,table_rows,auto_increment from tables where table_schema=‘pdb’; 查看自己的数据库中的纪录