mysql的主外键约束以及连接查询

1.–主外键具体讲解

–创建主表
–部门表

create table dept(
 did int ,
 dname VARCHAR(50),
 primary key (did,dname)
 );

–当然也可以后期再加主键约束

alter table dept
 add constraint  primary key pk_dept_id (did);

–创建从表
–员工表

create table employee(
	eid int ,
	ename varchar(50),
	did int ,
	primary key (eid),
	foreign key (did) references dept(did)
 );

–当然也可以后期再加上外键约束

alter table employee 
add constraint foreign key fk_employee_dept (did) references dept(did);

–当主表删除或者更新该值时,选中该值的列会怎么样呢

–四个选择
–1.cascade 删除选择该值的所有列
–2.set null 修改选中该值的所有列,进行null替换
(如果该字段被设置为not null 则操作不成功)
– 3.no action不进行任何操作
– 4.restrict(默认) 拒绝主表删除或者更新该列数据
–例句

alter table employee 
add constraint foreign key fk_employee_dept (did) references dept(did)
on cascade;

2.连接查询

1.交叉连接(一般很少用到)

select * from 表1 cross join 表2

2.内连接inner join (简单连接或者自然连接)
–方式1

select 查询字段 from 表1 inner join 表2 on 表1.字段=2.的字段;

–方式2

select 查询字段 from 表1,2 where 表1.字段=2.字段;

3.外连接
–左外连接

select 查询字段 from 表1 left join 表2 on 表1.字段=2.字段;

–右外连接

select 查询字段 from 表1 right join 表2 on 表1.字段=2.字段;

4.子查询
– 子查询是指一个查询语句嵌套在另一个查询语句内部的查询,在执行查询语句时,首先会执行子查
询中的语句,然后将返回的结果作为外层查询的过滤条件

select * from employee where did=(select did from dept where dname='技术部' );--查询部门为技术部的全部员工

–exists

select * from employee where exists(条件)--如果子查询存在,则返回true,否则返回false

–创建一个用于测试的t1表

create table t1(
	id int
	)
insert into t1(id) values(1);
insert into t1(id) values(2);
insert into t1(id) values(3);
--stu表
--插入数据
INSERT INTO `stu`(`id`, `name`, `score`, `subject`) VALUES (1, 'lxl', 99, '语文');
INSERT INTO `stu`(`id`, `name`, `score`, `subject`) VALUES (2, 'hah', 89, '语文');
INSERT INTO `stu`(`id`, `name`, `score`, `subject`) VALUES (3, 'ww', 49, '语文');
INSERT INTO `stu`(`id`, `name`, `score`, `subject`) VALUES (4, 'lxl', 78, '数学');
INSERT INTO `stu`(`id`, `name`, `score`, `subject`) VALUES (5, 'hah', 97, '数学');
INSERT INTO `stu`(`id`, `name`, `score`, `subject`) VALUES (6, 'ww', 98, '数学');

–any

select * from stu where id>any(select id from t1)--查询出stu所有id>1的数据
select * from stu where id<any(select id from t1)--查询出stu所有id<3的数据

–all

select * from stu where id>all(select id from t1)--查询出stu所有id>3的数据
select * from stu where id<all(select id from t1)--查询出stu所有id<1的数据
posted @ 2021-04-18 16:23  小吕不秃顶也能变强  阅读(26)  评论(0)    收藏  举报