[MySQL] 5 minutes to learn basic database operations (two)


Preface

Earlier we talked about MySQL's single-table operation. Now we have entered the MySQL multi-table operation part. In this chapter, we will
(1) learn to use ** inner join** for multi-table query, and be able to use ** left Outer join** and **Right outer join** perform multi-table query.
(2) Understand what a transaction is and how to use transactions in MySQL.
(3) Understand the concept of phantom reading
(4) Use DCL to manage users in MySQL

Tip: The following is the content of this article, the following cases are for reference

1. Multi-table query

1. Data preparation

# 创建部门表
create table dept(
id int primary key auto_increment,
name varchar(20) -- 部门名称
)
insert into dept (name) values ('开发部'),('市场部'),('财务部');
# 创建员工表
create table emp (
	id int primary key auto_increment,
	name varchar(10),
	gender char(1), -- 性别
	salary double, -- 工资
	join_date date, -- 入职日期
	dept_id int,
	foreign key (dept_id) references dept(id) -- 外键,关联部门表(部门表的主键)
)
insert into emp(name,gender,salary,join_date,dept_id) values('孙悟空','男',7200,'2013-02-24',1);
insert into emp(name,gender,salary,join_date,dept_id) values('猪八戒','男',3600,'2010-12-02',2);
insert into emp(name,gender,salary,join_date,dept_id) values('唐僧','男',9000,'2008-08-08',2);
insert into emp(name,gender,salary,join_date,dept_id) values('白骨精','女',5000,'2015-10-07',3);
insert into emp(name,gender,salary,join_date,dept_id) values('蜘蛛精','女',4500,'2011-03-14',1);

2. Cartesian product

Will make a matrix multiplication product according to table1*table2, and it will be a big Cartesian product table
principle: cross join returns all rows in the left table, and each row in the left table and all rows in the right table are one by one combination

select * from table2, table2 ;

3. Multi-table connection

Why connect?
Because in the actual development process, many times need to use the data in multiple tables at the same time

#直接多表连接,用from
#SELECT 字段名 FROM 左表, 右表 WHERE 条件
select t1.name, t1.sex, t1.age, t2.id 
from emp t1, dept t2
where t1.id = t2.id; -- 筛选条件,避免笛卡尔积

#inner可省略,on用来确定连接条件,where用来确定查询范围。
#SELECT 字段名 FROM 左表 [INNER] JOIN 右表 ON 条件
select * from emp inner join dept;
select * from emp inner join dept on emp.id = dept.id where ;
 
#左外连接:求交集(左边的表完全显示)
#SELECT 字段名 FROM 左表 LEFT [OUTER] JOIN 右表 ON 条件
select * from emp left join dept on emp.id = dept.id where ;

#SELECT 字段名 FROM 左表 RIGHT [OUTER ]JOIN 右表 ON 条件
select * from emp right join dept on emp.id = dept.id where ;

#子查询:【用一个查询的结果作为另外一个查询的条件】
#SELECT 查询字段 FROM 表 WHERE 字段 =(子查询);
#SELECT 查询字段 FROM 表 WHERE 字段 IN (子查询);

to sum up

To be continued

Guess you like

Origin blog.csdn.net/weixin_43801418/article/details/110918760