一丶表与表之间的关系
背景:
由于如果只使用一张表存储所有的数据,就会操作数据冗余,也会操作数据库查询效率低下等问题,所以会把一张表分成多个表. 但是表与表之间的关系就需要被,否则在创建数据库表时,思维混乱,导致项目崩溃.
表与表之间存在三种关系:
1.一对一
2.一对多
3.多对多
如何找出表与表之间关系:
分析步骤:
#1、先站在左表的角度去找
是否左表的多条记录可以对应右表的一条记录,如果是,则证明左表的一个字段foreign key 右表一个字段(通常是id)
#2、再站在右表的角度去找
是否右表的多条记录可以对应左表的一条记录,如果是,则证明右表的一个字段foreign key 左表一个字段(通常是id)
#3、总结:
#多对一:
如果只有步骤1成立,则是左表多对一右表
如果只有步骤2成立,则是右表多对一左表
#多对多
如果步骤1和2同时成立,则证明这两张表时一个双向的多对一,即多对多,需要定义一个这两张表的关系表来专门存放二者的关系
#一对一:
如果1和2都不成立,而是左表的一条记录唯一对应右表的一条记录,反之亦然。这种情况很简单,就是在左表foreign key右表的基础上,将左表的外键字段设置成unique即可
一对一:
含义:
1.将一对一的情况,当作是一对多情况处理,在任意一张表添加一个外键,并且这个外键要唯一,指向另外一张表主键.
2.直接将两张表合并成一张表将两张表的主键建立起连接,
3.让两张表里面主键相等
案例:
学生和客户,班级和班长, 公民和身份号码,国家和国旗都是一对一的关系
关联方式:foreign key+unique
# 1. 创建表
create table customer0(
id int primary key auto_increment,
name varchar(20) not null,
qq varchar(10) not null,
phone char(16) not null
);
create table student0(
id int primary key auto_increment,
class_name varchar(20) not null,
customer_id int unique, #该字段一定要是唯一的
foreign key(customer_id) references customer0(id) #外键的字段一定要保证unique
on delete cascade
on update cascade
);
# 查看student表的详细信息
#增加客户
mysql> insert into customer0(name,qq,phone) values
('韩蕾','31811231',13811341220),
('杨澜','123123123',15213146809),
('翁惠天','283818181',1867141331),
('杨宗河','283818181',1851143312),
('袁承明','888818181',1861243314),
('袁清','112312312',18811431230);
mysql> #增加学生
mysql> insert into student0(class_name,customer_id) values
('脱产1班',3),
('周末1期',4),
('周末1期',5);
一对多***:
含义:
1.A表中的某条数,可以被B表关联N条
2.在多的一方添加一个外键,指向一的一方的主键
案例:一个出版社可以出版多本书
关联方式:foreign key
# 1 . 创建出版社表
create table press(
id int primary key auto_increment,
name varchar(20)
);
# 2. 创建图书表
create table books1(
bid int primary key auto_increment,
name char(10),
press_id int not null,
foreign key(press_id) references press(id)
on delete cascade on update cascade
);
# 3. 查看books表详细结构
mysql> show create table books;
`name` char(10) DEFAULT NULL,
`press_id` int(11) NOT NULL,
PRIMARY KEY (`bid`),
KEY `press_id` (`press_id`),
CONSTRAINT `books_ibfk_1` FOREIGN KEY (`press_id`) REFERENCES `press` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 |
# 4. 增加数据
# press表
mysql> insert into press(name) values('北京工业书出版社'),('人民出版社');
Query OK, 2 rows affected (0.12 sec)
Records: 2 Duplicates: 0 Warnings: 0
# books表
mysql> insert into books(name,press_id) values('柴嘉欣',1),('精益求精',2);
Query OK, 2 rows affected (0.11 sec)
Records: 2 Duplicates: 0 Warnings: 0
多对多***:
含义:
1.引入第三张的概念,
2. 建立一张中间表,将多对多的关系,拆分成一对多的关系,中间表至少要有两个外键,分别指向原来的那两张表
关联方式:
foreign key + 一张新的表
# 1. 创建图书表
create table books1(
bid int primary key auto_increment,
name char(10)
);
# 2. 创建作者表
create table author(
aid int primary key auto_increment,
name varchar(20)
);
# 3. 第三张表
create table au_bo(
id int not null unique auto_increment,
author_id int not null,
book_id int not null,
# 给外键起名 ,fk_book ,
constraint fk_book foreign key(book_id) references books1(bid)
on update cascade
on delete cascade,
# 给外键起名 ,fk_auto ,
constraint fk_auto foreign key(author_id) references author(aid)
on update cascade
on delete cascade,
primary key(author_id,book_id)
);
# 4. 查看au_bo表结构
mysql> show create table au_bo;
| au_bo | CREATE TABLE `au_bo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`author_id` int(11) NOT NULL,
`book_id` int(11) NOT NULL,
PRIMARY KEY (`author_id`,`book_id`),
UNIQUE KEY `id` (`id`),
KEY `fk_book` (`book_id`),
CONSTRAINT `fk_auto` FOREIGN KEY (`author_id`) REFERENCES `author` (`aid`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_book` FOREIGN KEY (`book_id`) REFERENCES `books1` (`bid`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
# 5. 增加数据
mysql> insert into au_bo(author_id,book_id) values(1,1),(1,2),(2,1),(2,2),(3,2),(3,4);
+----+-----------+---------+
| id | author_id | book_id |
+----+-----------+---------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 3 | 2 |
| 7 | 3 | 4 |
+----+-----------+---------+
二丶增删改查操作
表操作
1.创建表 create table 表名
2.删除表 drop table 表名
3.查看表结构 desc 表名 / show create table 表名
4.修改表如下👇:
### 修改表
# 1. 修改表名
alter table 旧表名 rename 新表名;
# 2. 添加新字段 (新字段默认添加表的最后)
alter table 表名 add 新字段 类型(宽度) 约束;
# 3. 在已有 id 字段前,添加新的字段
alter table 表名 add 新字段 类型(宽度) 约束 first id;
# 4. 在已有 id 字段后,添加新的字段
alter table 表名 add 新字段 类型(宽度) 约束 after id;
# 5. 删除 字段名
alter table 表名 drop 字段名;
# 6. 更改字段名 或约束 使用 change
alter table 表名 change 旧字段 新字段 类型(宽度) 约束
# change name username char(12) not null
# change name name char(12) not null
# change name name varchar(255) after id;
# 7. 只更新字段的类型或越是
alter table 表名 modify 存在的字段 新类型(宽度) 约束
# modify name char(12) unique ;
# modify name char(12) unique after id;
数据操作
增加:
# 添加一条信息
insert into 表名 value(id1,name1);
# 添加多条信息
insert into 表名 vlaues(id1,name1) ,(id2,name2),(id3,name3);
# 指定字段插入
insert into 表名(name) values('abc'),('123'),('张三');
# 添加 查询信息 ,字段要一一对应
insert into 表1(name,gender) select username,sex from 表2;
删除:
# 删除表内所有数据 ,(如果主键存在自增,delete 不能清除主键自增信息)
delete from 表名;
# 指定条件删除
delete from 表名 where 条件;
修改:
# 修改一个值
update 表名 set 字段=新值1 where 条件
# 修改多个值
update 表名 set 字段1=值1,字段2=值2 where 条件
查询👇:
# 单表查询 # 多表查询
三丶单表查询
单标查询语法:
SELECT DISTINCT 字段1,字段2... FROM 表名 WHERE 条件 GROUP BY field HAVING 筛选 ORDER BY field LIMIT 限制条数
关键字执行的优先级
#3## 特别重要 👇 from :找到表:from where :拿着where指定的约束条件,去文件/表中取出一条条记录 group by :将取出的一条条记录进行分组group by,如果没有group by,则整体作为一组 select :执行select distinct :去重 having :将分组的结果进行having过滤 order by : 将结果按条件排序:order by desc降序 acs升序 limit :限制结果的显示条数
建表:
# 创建表 company.employee 员工id id int 姓名 emp_name varchar 性别 sex enum 年龄 age int 入职日期 hire_date date 岗位 post varchar 职位描述 post_comment varchar 薪水 salary double 办公室 office int 部门编号 depart_id int #创建表 create table employee( id int not null unique auto_increment, emp_name varchar(20) not null, sex enum('male','female') not null default 'male', #大部分是男的 age int(3) unsigned not null default 28, hire_date date not null, post varchar(50), post_comment varchar(100), salary double(15,2), office int, #一个部门一个屋子 depart_id int ); #查看表结构 mysql> desc employee; +--------------+-----------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------------+-----------------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | emp_name | varchar(20) | NO | | NULL | | | sex | enum('male','female') | NO | | male | | | age | int(3) unsigned | NO | | 28 | | | hire_date | date | NO | | NULL | | | post | varchar(50) | YES | | NULL | | | post_comment | varchar(100) | YES | | NULL | | | salary | double(15,2) | YES | | NULL | | | office | int(11) | YES | | NULL | | | depart_id | int(11) | YES | | NULL | | +--------------+-----------------------+------+-----+---------+----------------+ #插入记录 #三个部门:教学,销售,运营 insert into employee(emp_name,sex,age,hire_date,post,salary,office,depart_id) values ('egon','male',18,'20170301','老男孩驻沙河办事处外交大使',7300.33,401,1), #以下是教学部 ('alex','male',78,'20150302','teacher',1000000.31,401,1), ('wupeiqi','male',81,'20130305','teacher',8300,401,1), ('yuanhao','male',73,'20140701','teacher',3500,401,1), ('liwenzhou','male',28,'20121101','teacher',2100,401,1), ('jingliyang','female',18,'20110211','teacher',9000,401,1), ('jinxin','male',18,'19000301','teacher',30000,401,1), ('成龙','male',48,'20101111','teacher',10000,401,1), ('歪歪','female',48,'20150311','sale',3000.13,402,2),#以下是销售部门 ('丫丫','female',38,'20101101','sale',2000.35,402,2), ('丁丁','female',18,'20110312','sale',1000.37,402,2), ('星星','female',18,'20160513','sale',3000.29,402,2), ('格格','female',28,'20170127','sale',4000.33,402,2), ('张野','male',28,'20160311','operation',10000.13,403,3), #以下是运营部门 ('程咬金','male',18,'19970312','operation',20000,403,3), ('程咬银','female',18,'20130311','operation',19000,403,3), ('程咬铜','male',18,'20150411','operation',18000,403,3), ('程咬铁','female',18,'20140512','operation',17000,403,3) ; #ps:如果在windows系统中,插入中文字符,select的结果为空白,可以将所有字符编码统一设置成gbk
简单查询:select
### 使用函数 select user(); # 获取当前用户 select database(); # 获取当前数据库 select now(); # 获取当前时间 ### 简单查询 # 查询全部字段 SELECT id,emp_name,sex,age,hire_date,post,post_comment,salary,office,depart_id FROM employee; # 查所有 SELECT * FROM employee; # 查询指定字段 SELECT emp_name,salary FROM employee; ### 查询去重 distinct # 查看有几个部门 select distinct post from employee; ### 查询通过四则运算 # 查看 每个人的年薪 select emp_name, salary*12 from emplpoyee; ### 更改别名 # as select emp_name, salary*12 AS Annual_salary from employee; # 字段后直接跟别名 select emp_name, salary*12 Annual_salary from employee; ### 定义显示格式 # CONCAT()函数: 字段与分隔符号 以逗号间隔 select concat('姓名:',emp_name,'年薪:',salary*12) from employee; # CONCAT_WS()函数: 第一个参数必须是分隔符, select concat_ws(':' , emp_name, salary*12) from employee; # 结合CASE 语句: #语法: ( case when 条件1 then 显示内容 when 条件2 then 显示内容 else 显示内容 end ) select ( case when emp_name='jingliyang' then emp_name when emp_name='alex' then concat(emp_name,'_BIGSB') else concat(emp_name,'SB') end ) as new_name from employee; #### 练习: #1 查出所有员工的名字,薪资,格式为 <名字:egon> <薪资:3000> # select concat('<名字:',emp_name,'>'),concat('<薪资:',salary,'>') from employee; #2 查出所有的岗位(去掉重复) # select distinct post from employee; #3 查出所有员工名字,以及他们的年薪,年薪的字段名为annual_year # select emp_name ,salary*12 from employee;
Where查询:
### 常用的模式 # 比较运算符: > 大于, < 小于, >= 大于等于, <=小于等于 , != 不等于, <> 不等于 # between 80 and 100 : 在80 到 100 的范围内, 包含 80 和 100 # in(80,90,100) : 值是80 或者 90 或者 100 # 模糊查询 # like : % 表示任意多个字符, _表示一个字符 # 1. like 'a%' 以a开头的. # 2. like '%a' 以a结尾的 # 3. like '_a' Xa 两个字符 # 4. like 'a_' aX 两个字符 # regexp :正则匹配 # 1. '^a' 以a开头 # 2. '\d+' 纯数字 # 3. 'a$' 以a结尾 # is 和 is not is null : 是空 is not null : 非空 # 逻辑运算符: and与 or或 not非
where案例
# 1. 条件查询 select emp_name from employee where post='sale'; # 2. 多条件查询 select emp_name , salary from employee where port='teacher' and salary>10000; # 3.关键字 between and select emp_name ,salary from employee where salary beetween 10000 and 20000; # 4.关键字 is null 判断某个字段是不是空,不能用等号 select emp_name,post_comment from employee where post_comment is null; select emp_name,post_comment from employee where post_comment is not null; # 判断是不是 select emp_name,post_comment from employee where post_comment='' ; # 5.关键字IN集合查询 SELECT emp_name,salary FROM employee WHERE salary=3000 OR salary=3500 OR salary=4000 OR salary=9000 ; SELECT emp_name,salary FROM employee WHERE salary IN (3000,3500,4000,9000) ; SELECT emp_name,salary FROM employee WHERE salary NOT IN (3000,3500,4000,9000) ; # 6.关键字LIKE模糊查询 通配符 '%' 多个字符 # 查询eg开头 select * from employee where emp_name like 'eg%'; 通配符 '_' 单个字符 # select * from employee where emp_name like 'al__'; # 7 . regexp 依据正则匹配数据 # 找到以jin开头的数据 select emp_name ,salary*12 from employee where emp_name regexp '^jin' ### 练习 1. 查看岗位是teacher的员工姓名、年龄 # select emp_name , age from employee where post ='teacher'; 2. 查看岗位是teacher且年龄大于30岁的员工姓名、年龄 # select emp_name , age from employee where post ='teacher' and age>30; 3. 查看岗位是teacher且薪资在9000-10000范围内的员工姓名、年龄、薪资 # select emp_name , age ,salary*12 from employee where post ='teacher' and salary between 9000 and 10000; 4. 查看岗位描述不为NULL的员工信息 # select * from employee where post_comment is not null; 5. 查看岗位是teacher且薪资是10000或9000或30000的员工姓名、年龄、薪资 # select emp_name , age ,salary from employee where post ='teacher' and salary in (9000,10000,30000); # select emp_name , age ,salary from employee where post ='teacher' and salary=9000 or salary=10000 or salary=30000; 6. 查看岗位是teacher且薪资不是10000或9000或30000的员工姓名、年龄、薪资 # select emp_name , age ,salary from employee where post ='teacher' and salary not in (9000,10000,30000); # select emp_name , age ,salary from employee where post ='teacher' and not (salary=9000 or salary=10000 or salary=30000); 7. 查看岗位是teacher且名字是jin开头的员工姓名、年薪 # select emp_name ,salary*12 from employee where post='teacher' and emp_name like 'jin%'; # select emp_name ,salary*12 from employee where post='teacher' and emp_name regexp '^jin';
GROUP BY 分组查询:
特点:
根据某个重复率比较高的字段进行的
一旦分组了就不能对具体的一条数据进行操作
group_concat():只用来做最重的显示,不能作为中间的结果操作其他数据
分组具有去重的效果
### 单独使用group by 关键字分组查询 . 每次操作都是以组的形式操作这些数据 # 按照部门进行分组,获得每个部门的名字 (有去重的效果) select post from employee group by post; ### group by 和 group_concat()函数一起使用 # group_concat()只是用来显示内容 # 按照岗位分组,并查看组内所有成员 select post,group_concat(emp_name) from employee group by post; ### group by 和 聚合函数 一起使用 # 按照岗位分组,并查看每组有多少人 select post,count(id) as count for employee group by post; ##### 强调 1.如果我使用 unique 字段作为分组依据, 则每条记录自成一组,这样没有意义 2. 通常多条记录之间的某个字段值相同,该字段通常用来作为分组的依据
HAVING 组过滤:
特点:
对一个组进行条件筛选
优先级:
where > group by > having
1.where发生在分组group by之前,where可以有任意字段,where绝对不会和聚合函数一起使用.
2.having发生在分组group by之后,因而having可以使用分组的字段,单无法直接取到其他字段
## 验证 1. mysql> select post from employee where count(salary) group by post; ERROR 1111 (HY000): Invalid use of group function ## 验证 2. #错误,分组后无法直接取到salary字段 mysql> select post,group_concat(emp_name) from employee group by post having salary>1000; ERROR 1054 (42S22): Unknown column 'salary' in 'having clause' #可以使用聚合函数获取未定义字段信息 mysql> select post,group_concat(emp_name) from employee group by post having avg(salary)>10000; +-----------+---------------------------------------------------------+ | post | group_concat(emp_name) | +-----------+---------------------------------------------------------+ | operation | 程咬铁,程咬铜,程咬银,程咬金,张野 | | teacher | 成龙,jinxin,jingliyang,liwenzhou,yuanhao,wupeiqi,alex | +-----------+---------------------------------------------------------+ ### 练习 1. 查询各岗位内包含的员工个数小于2的岗位名、岗位内包含员工名字、个数 # select post, count(id),group_concat(emp_name) from employee group by post having count(id)<2; 3. 查询各岗位平均薪资大于10000的岗位名、平均工资 # select post,avg(salary) from employee group by post having avg(salary)>10000; 4. 查询各岗位平均薪资大于10000且小于20000的岗位名、平均工资 # select post,avg(salary) from employee group by post having avg(salary)>10000 and avg(salary)<20000; # select post,avg(salary) from employee group by post having avg(salary) between 10000 and 20000;
聚合函数:
count() :统计某个字段出现的次数
max() : 某个字段的最大值
min() : 某个字段的最小值
avg() : 某个字段的平均值
sum() : 某个字段进行求和
### 如果没有进行分组, 那么这张表会作为一个整体成为一组 ### 应用实例 # 统计这张表有多少条记录 select count(*) from employee; # 统计这个表id字段有效值有多少个.(有效值 指的是非空) select count(id) from employee; # 最高的工资 select max(salary) from employee; # 最低的工资 select min(salary) from employee; # 平均工资 select avg(salary) from employee; # 工资总和 select sum(salary) from employee; ### 练习 1. 查询岗位名以及岗位包含的所有员工名字 # select post, group_concat(emp_name) from employee group by post; 2. 查询岗位名以及各岗位内包含的员工个数 # select post, count(emp_name) from employee group by post; 3. 查询公司内男员工和女员工的个数 # select count(emp_name),sex from employee group by sex; 4. 查询岗位名以及各岗位的平均薪资 # select post, avg(salary) from employee group by post ; 5. 查询岗位名以及各岗位的最高薪资 # select post, max(salary) from employee group by post ; 6. 查询岗位名以及各岗位的最低薪资 # select post, min(salary) from employee group by post ; 7. 查询男员工与男员工的平均薪资,女员工与女员工的平均薪资 # select sex, max(salary) from employee group by sex ; # 求各部门薪资大于1w的人的个数 select post,count(id) from employee where salary >10000 group by post;
ORDER BY 排序查询:
特点:
1.对单字段, 对多字段进行排序
2.默认升序 从小到大
3.desc 降序 从大到小, asc 升序 从小到大
### 按单列排序 # 升序排序工资 select * from employee order by salary; # asc 升序 select * from employee order by salary asc; # desc 降序 select * from employee order by salary desc; ### 按多列排序: # 先排age 升序 ,再排 薪资 升序 select * from employee order by age , salary ; # 先排age 降序 ,再排 薪资 升序 select * from employee order by age desc , salary ; ### 练习 1. 查询所有员工信息,先按照age升序排序,如果age相同则按照hire_date降序排序 # select * from employee order by age , hire_date desc; 2. 查询各岗位平均薪资大于10000的岗位名、平均工资,结果按平均薪资升序排列 # select post , avg(salary) from employee group by post having avg(salary)>10000 order by avg(salary); 3. 查询各岗位平均薪资大于10000的岗位名、平均工资,结果按平均薪资降序排列 # select post , avg(salary) from employee group by post having avg(salary)>10000 order by avg(salary) desc;
LIMIT限制查询:
特点:
1.limit(n,m) : n默认从0开始 , 从n+1开始, 取m条
2.与 limit n offset m : 用法一直
3.limit(n) : 取n条
4.和order by 搭配使用
应用:
1.分页
2.限制取值
## 实例 # 降序排序工资,每次取 3 条 select * from employee order by salary desc limit(3); # 从第1条开始,即查出第一条,包含这一条并继续查询5条 select * from employee order by salary desc limit 0,5; # 从第6条开始,即查出第6条,包含这一条并继续查询5条 select * from employee order by salary desc limit 5,5; ### 分页练习 分页显示,每页5条 mysql> select * from employee limit 0,5; +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+ | id | emp_name | sex | age | hire_date | post | post_comment | salary | office | depart_id | +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+ | 1 | egon | male | 18 | 2017-03-01 | 老男孩驻沙河办事处外交大使 | NULL | 7300.33 | 401 | 1 | | 2 | alex | male | 78 | 2015-03-02 | teacher | NULL | 1000000.31 | 401 | 1 | | 3 | wupeiqi | male | 81 | 2013-03-05 | teacher | NULL | 8300.00 | 401 | 1 | | 4 | yuanhao | male | 73 | 2014-07-01 | teacher | NULL | 3500.00 | 401 | 1 | | 5 | liwenzhou | male | 28 | 2012-11-01 | teacher | NULL | 2100.00 | 401 | 1 | +----+-----------+------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+ mysql> select * from employee limit 5,5; +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+ | id | emp_name | sex | age | hire_date | post | post_comment | salary | office | depart_id | +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+ | 6 | jingliyang | female | 18 | 2011-02-11 | teacher | NULL | 9000.00 | 401 | 1 | | 7 | jinxin | male | 18 | 1900-03-01 | teacher | NULL | 30000.00 | 401 | 1 | | 8 | 成龙 | male | 48 | 2010-11-11 | teacher | NULL | 10000.00 | 401 | 1 | | 9 | 歪歪 | female | 48 | 2015-03-11 | sale | NULL | 3000.13 | 402 | 2 | | 10 | 丫丫 | female | 38 | 2010-11-01 | sale | NULL | 2000.35 | 402 | 2 | +----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+ 5 rows in set (0.00 sec)
正则查询:
特点:
mysql可以使用正则进行查询
## 实例 # emp_name字段以al开头的数据 select * from employee where emp_name regexp '^al'; # emp_name字段以on结尾的数据 select * from employee where emp_name regexp 'on$'; # emp_name字段以al开头的数据 select * from employee where emp_name regexp '^al';