外键变种与单、多表查询

一、外键变种
三种关系:
---多对一
站在左表的角度:
(1)一个员工能否对应多个部门;
(2)多个员工 能否在一个部门
只要一个条件成立: 多对一或者一对多
如果两个条件都成立:多对多
---- 多对多
create table book(
id int primary key auto_increment,
name varchar(20)
);
create table author(
id int primary key auto_increment,
name varchar(20)
);
create table author2book(
id int primary key auto_increment,
author_id int not null,
book_id int not null,

constraint fk_author foreign key(author_id) references author(id)
on delete cascade
on update cascade,

constraint fk_book foreign key(book_id) references book(id)
on delete cascade
on update cascade
);
---一对一
#两张表: 用户表(user)和博客表(blog)
#创建用户表
create table user(
id int primary key auto_increment,
name varchar(20)
);
#创建博客表
create table blog(
id int primary key auto_increment,
url varchar(100),
user_id int unique,
constraint fk_user foreign key(user_id) references user(id)
on delete cascade
on update cascade
);
#插入用户表中的记录
insert into user(name) values
('alex'),
('wusir'),
('egon'),
('xiaoma')
;
# 插入博客表的记录
insert into blog(url,user_id) values
('http://www.cnblog/alex',1),
('http://www.cnblog/wusir',2),
('http://www.cnblog/egon',3),
('http://www.cnblog/xiaoma',4)
;
as #给字段起别名
#子查询
select url as user_url from blog where user_id = (select id from user where name = 'wusir');
二、单表查询
关键字的执行优先级
from
where
group by
having
select
distinct
order by
limit
1.找到表:form
2.拿着where制定的约束条件,去文件/表中取出一条条记录
3.将取出的一条条记录进行分组group by,如果没有group by,则整体视为一组;分组的目的是将表中具有
相同属性的值筛选出来便于处理
4.将分组的结果进行having过滤
5.执行select
6.使用distinct去重
7.将结果按条件排序: order by
8.限制结果的显示条数:limit

查询岗位名以及岗位包含的所有员工名字 group_concat(name)
select post,group_concat(name) from employee group by post;

三、多表查询:
根据之前的学习将两张表间进行连接,不建立外键约束
select * from employee where dep_id=(select id from department);

select * from employee,department;
#会形成一个笛卡尔积
select * from employee,department where employee.dep_id = department.id;
-内连接:只连接匹配的行
select * from employee inner join department on employee.dep_id=department.id;

-左连接:优先匹配左表的记录
select * from employee left join department on employee.dep_id=department.id;
-右连接:优先匹配右表的记录
select * from employee right join department on employee.dep_id=department.id;

-子查询:
#1:子查询是将一个查询语句嵌套在另一个查询语句中;
#2:内层查询语句的查询结果,可以为外层查询语句提供查询条件;
#3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字
#4:还可以包含比较运算符:= 、 !=、> 、<等

猜你喜欢

转载自www.cnblogs.com/wr13640959765/p/9567020.html