Mysql优化之7种表连接从此不怕写SQL
1. 引言
作为一个开发人员需要掌握数据库的哪些东西?
在开发中涉及到数据库,基本上只用到了sql语句,如何写sql以及对其进行优化就比较重要,那些mysql的厚本书籍针对的是DBA,我们只需要学习其中的sql就可以了,但是随着行业发展现在越来越多的企业需要我们成长为一个全栈式工程师,所以在面试中,经常会被问道sql优化的解决方案?你们的项目中如何对mysql进行调优的?等等,如果你还没有掌握优化相关的知识这个系列的博客我们一起来看看。
2. MySQL优化必须掌握的点
1. Mysql的执行顺序,这个是写sql的核心,在项目开发过程汇总很多错误就是因为对其不了解;
2. 7种连接不怕写sql
3. Mysql的索引相关的概念
4. explain关键字的使用
5. 如何进行多表查询,优化,这个是很重要的部分。
3. SQL的书写顺序
我们在操作数据库时一般使用sql语句,我们手写的sql语句一般为:
select distinct
fields
from
left_table join_type
join
right_table
on join_condition
where
where_condition
group by group_fields
having having_condition
order by order_by_condition
limit limit_number
这是sql语句的书写顺序,这个sql的书写顺序可以重点关注一下。
4. SQL的执行顺序
from left_table
on join_condition
join_type join right_table
where where_condition
group by group_by_list
having having_condition
select distinct fields
order by order_by_condition
limit limit_number
5. 7种表连接方式
---部门表
DROP TABLE IF EXISTS `t_dept`;
CREATE TABLE `t_dept` (
`id` varchar(40) NOT NULL,
`name` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
---员工表
DROP TABLE IF EXISTS `t_emp`;
CREATE TABLE `t_emp` (
`id` varchar(40) NOT NULL,
`name` varchar(40) DEFAULT NULL,
`age` int(3) DEFAULT NULL,
`deptid` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `deptid` (`deptid`),
CONSTRAINT `deptid` FOREIGN KEY (`deptid`) REFERENCES `t_dept` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--插入部门数据
BEGIN;
INSERT INTO `t_dept` VALUES ('1', '研发部');
INSERT INTO `t_dept` VALUES ('2', '教学部');
INSERT INTO `t_dept` VALUES ('3', '小卖部');
INSERT INTO `t_dept` VALUES ('4', '高粱部');
COMMIT;
--插入员工数据
BEGIN;
INSERT INTO `t_emp` VALUES ('1', '张三', 23, '1');
INSERT INTO `t_emp` VALUES ('2', '李四', 25, '2');
INSERT INTO `t_emp` VALUES ('3', '王五', 27, '1');
INSERT INTO `t_emp` VALUES ('4', '小黑', 43, NULL);
COMMIT;
1. 查询共有数据
select * from t_emp e
inner join t_dept d
on e.deptid = d.id
2. 查询左表数据为主
select * from t_emp e
LEFT join t_dept d
on e.deptid = d.id
3. 右表数据为主
select * from t_emp e
right join t_dept d
on e.deptid = d.id
4. 查询左表数据中与右表没有关系的数据
select * from t_emp e
left join t_dept d
on e.deptid = d.id
where e.deptid is null
5. 查询右表数据中与左表没有关系的数据
select * from t_emp e
right join t_dept d
on e.deptid = d.id
where e.id is null
6. 全连接
select * from t_emp e
left join t_dept d
on e.deptid = d.id
UNION
select * from t_emp e
right join t_dept d
on e.deptid = d.id
7. 查询两张表中没有关系的数据之和
select * from t_emp e
left join t_dept d
on e.deptid = d.id where e.deptid is null
UNION
select * from t_emp e
right join t_dept d
on e.deptid = d.id where e.id is null