当前位置:网站首页>MySQL - multi table query
MySQL - multi table query
2022-07-29 07:12:00 【m0_ sixty-seven million four hundred and one thousand two hundr】
MySQL---- Multi-table query
Multi table relation
When designing the database table structure , According to the business requirements and the relationship between business modules , Analysis and design table structure , Because businesses are interrelated , Therefore, there are also various connections between various table structures
The connection between tables :
1. One to many ( For one more )
2. Many to many
3. one-on-one
One to many ( For one more )
for example , One employee corresponds to one department , A department can correspond to multiple employees
Usually create a foreign key on the side of more than one , Point to the side of one
Employees and departments , Set foreign keys on the employee table , Point to the Department table
Many to many
for example , A student can take more than one course , A course can be taken by more than one student
A third table is usually created , Contains at least two foreign keys , Point to the primary keys of the two tables
one-on-one
for example , The relationship between users and their academic information , One person only corresponds to one piece of education information
You can add foreign keys on either side , Associate the primary key of the other party , And set the foreign key to be unique (unique)
notes : It can be put in a table , But split it , Put basic information in a table , Put the details in another table , It can improve the operation efficiency
Multi-table query
summary :
Query data from multiple tables
The cartesian product :
Cartesian product is two sets ( Two tables ) The result of pairwise combination of each data in
Cartesian product will be generated in multi table query , To eliminate the Cartesian product by adding conditions
dept surface :
emp surface :
The query produces the result of Cartesian product :
select * from emp, dept ;
Eliminate Cartesian product ( Adding conditions ):
select * from emp, dept where emp.dept_id=dept.id;
Classification of multi table query
1. Link query :
Internal connection :
It is equivalent to a query AB The intersection of
External connection :
The left outer join :
Inquire about A All data for , Splice at the same time B Corresponding data
Right connection :
Inquire about B All data for , Splice at the same time A The corresponding data in
Self join :
Table and its own connection query
Self join must alias the table
2. Subquery
Data preparation
Departmental table :
create table dept (
id int auto_increment primary key comment 'id',
name varchar(50) not null comment ' Department name '
) comment ' Departmental table ';
insert into dept (id, name)
values (1, ' R & D department '),
(2, ' The Marketing Department '),
(3, ' Finance Department '),
(4, ' The sales department '),
(5, ' General manager office '),
(6, ' The personnel department ');
The employee table :
create table emp(
id int auto_increment primary key ,
name varchar(50) not null ,
age int,
job varchar(20) comment ' Position ',
salary int ,
entrydate date comment ' Entry time ',
managerid int comment ' Direct leadership id',
dept_id int comment ' Department id'
) comment ' The employee table ';
insert into emp
values ( 1, ' Jin yong ', 66, ' President ', 20000, '2000-01-01', null, 5 ),
( 2, ' zhang wuji ', 20, ' project manager ', 12500, '2005-12-05', 1, 1 ),
( 3, ' Yang Xiao ', 33, ' Development ', 8400, '2000-11-03', 2, 1 ),
( 4, ' Xiangr ', 48, ' Development ', 11000, '2002-02-05', 2, 1 ),
( 5, ' Chen Yucun ', 43, ' Development ', 10500, '2004-09-07', 3, 1 ),
( 6, ' Small zhao ', 19, ' Programmers encourage teachers to ', 6600, '2004-10-12', 2, 1 ),
( 7, ' extinction ', 60, ' Chief financial officer ', 8500, '2002-09-12', 1, 3 ),
( 8, ' Zhou Zhiruo ', 19, ' accounting ', 48000, '2006-06-02', 7, 3 ),
( 9, ' Ding Minjun ', 23, ' Cashier ', 5250, '2009-05-13', 7, 3 ),
( 10, ' Zhao Min ', 20, ' Director of marketing department ', 12500, '2004-10-12', 1, 2 ),
( 11, ' Deer stick guest ', 56, ' staff member ', 3750, '2006-10-03', 10, 2 ),
( 12, ' Hebiwen ', 19, ' staff member ', 3750, '2007-05-09', 10, 2 ),
( 13, ' Oriental White ', 19, ' staff member ', 5500, '2009-02-12', 10, 2 ),
( 14, ' Zhang Sanfeng ', 88, ' Sales Director ', 14000, '2004-10-12', 1, 4 ),
( 15, ' Yuliangzhou ', 38, ' sales ', 4600, '2004-10-12', 14, 4 ),
( 16, ' Song Yuanqiao ', 40, ' sales ', 4600, '2004-10-12', 14, 4 ),
( 17, ' Chen Youlang ', 42, null, 2000, '2011-10-12', 1, null );
Internal connection
grammar :
# Implicit inner join
select Field list from surface 1, surface 2 where Conditions ;
# Display inner connection
select Field list from surface 1 [inner] join surface 2 on Connection condition ;
The inner join query is the part of the intersection of two tables
# Query the name of each employee and the name of the associated department
select emp.name, dept.name from emp, dept where emp.dept_id=dept.id;
select emp.name, dept.name from emp inner join dept on emp.dept_id = dept.id;
External connection
grammar :
# The left outer join
select Field list from surface 1 left [outer] join surface 2 on Conditions ;
# Right connection
select Field list from surface 1 right [outer] join surface 2 on Conditions ;
The left outer join is equivalent to a query table 1 All of the data contained in the table 1 And table 2 Some data of intersection
Right outer join is equivalent to query table 2 All of the data contained in the table 1 And table 2 The data of the intersection part
# Inquire about emp All data of table , And corresponding department information ( Left )
select emp.*, dept.* from emp left outer join dept on emp.dept_id = dept.id;
# Inquire about dept All data of table , And employee information for ( Right )
select dept.*, emp.* from emp right outer join dept on emp.dept_id = dept.id;
The left outer connection and the right outer connection can be transformed into each other
Self join
grammar :
select Field list from surface a Alias a join surface a Alias b on Conditions ;
The self link query can be an internal connection query or an external connection query
# Query the names of employees and their leaders
# Self join can be viewed as two identical tables for join query
select a.name, b.name from emp a join emp b on a.managerid=b.id;
The joint query
union、union all
For joint query, the results of multiple queries are merged , Form a new query result set
grammar :
select Field list from surface a
union [all]
select Field list from surface b
# Lower salary than 5000 Of employees and older than 50 Of employees
select * from emp where salary>5000
union all
select * from emp where age>50;
# No, all If the condition is met repeatedly, it only occurs once
# Lower salary than 5000 Of employees and older than 50 Of employees
select * from emp where salary>5000
union
select * from emp where age>50;
The number of columns in multiple tables of joint query must be consistent , Field types should also be consistent
union all All the data will be merged directly ,union The merged data will be de duplicated
Subquery
Concept :SQL Nested in statement select Statement is a nested query , Also known as subquery select * from surface 1 where Field =(select Field from surface 2);
Statements outside the subquery can be insert、update、delete、select One of them
According to the structure of sub query , It is divided into :
Scalar subquery : The result of the subquery is a single value
Column query : The result of the subquery is a column
Line sub query : The result of the subquery is one row
Table sub query : The result of subquery is multi row and multi column
According to the location of subquery , It is divided into :
where after
from after
select after
Scalar subquery
The result returned by the subquery is a single value ( Numbers 、 character string 、 Date, etc. ), The simplest form , This seed query is called a scalar subquery
Common symbols :=、<>、>、>=、<、<=
# According to the sales department id Query employee information
# First, query separately
# Query the sales department id
select id from dept where name=' The sales department '; #id by 4
# Query the information of employees in the sales department
select * from emp where dept_id=4;
# Merge into one query
select * from emp where dept_id=(select dept.id from dept where dept.name=' The sales department ' );
Column query
The result of the subquery is a column ( It can be multiple lines ) Of , This sub query is a column sub query
Common operators :
# Column query
# Query all employee information of sales department and marketing department
# Check the sales and marketing department id
select id from dept where name=' The sales department ' or name=' The Marketing Department '; #id by 2 4
# Query all employees in both departments
select * from emp where dept_id in (2,4);
# Merge
select * from emp where dept_id in (select id from dept where name=' The sales department ' or name=' The Marketing Department ');
Line sub query
The result returned by the subquery is a row ( It can be multiple columns ), This sub query is a row sub query
Common operators :=、<>、in、not in
# Query the same employee information as Zhang Wuji's salary and direct leaders
# Inquire about Zhang Wuji's salary and direct leaders
select salary, managerid from emp where name=' zhang wuji ';
# Query the same employee information as Zhang Wuji's salary and direct leaders
select * from emp where (salary,managerid)=(select salary, managerid from emp where name=' zhang wuji ');
Table sub query
The result of subquery is multi row and multi column. This kind of query is table subquery
Common operators :in
# Query the employee information that is the same as the position and salary of Lu zhanke and song Yuanqiao
select * from emp where (job, salary) in ( select job, salary from emp where name in (' Deer stick guest ', ' Song Yuanqiao '));
The sub tables of the table sub query are used as temporary tables
# The date of employment inquiry is ’2006-01-01‘ After that, employee information and department information
# First, check the entry and exit positions ’2006-01-01‘ After that, all the information of the employees
# Connect to the left of the Department table
select e.*, dept.* from (select * from emp where entrydate>'2006-01-01') e left outer join dept on e.dept_id=dept.id;
Multi table query case
Data preparation :
create table salgrade (
grade int,
losal int comment ' The minimum limit of this salary grade ',
hisal int comment ' The highest limit '
) comment ' Salary scale ';
insert into salgrade values (1,0,3000);
insert into salgrade values (2,3001,5000);
insert into salgrade values (3,5001,8000);
insert into salgrade values (4,8001,10000);
insert into salgrade values (5,10001,15000);
insert into salgrade values (6,15001,20000);
insert into salgrade values (7,20001,25000);
insert into salgrade values (8,025001,30000);
1. Check the name of the employee , Age , Position , Department information ( Implicit inner join )
select e.name, e.age, e.job, d.*
from emp e, dept d
where e.dept_id=d.id;
2. The query age is less than 30 The name of the employee 、 Age 、 Position 、 Department information ( Display inner connection )
select e.name,e.age,e.job,d.*
from emp e
inner join dept d on e.dept_id = d.id
where e.age<30;
3. Query the Department with employees id, Department name
select distinct d.id,d.name
from emp e, dept d
where d.id=e.dept_id;
4. Query all ages greater than 40 The employees' , And the name of the Department to which it belongs , If the employee has no assigned department, it should also display
select e.*,d.name
from emp e
left outer join dept d on e.dept_id = d.id
where e.age>40;
5. Query the salary grade of all employees
select e.*,s.grade
from emp e, salgrade s
where e.salary between s.losal and s.hisal;
6. Query the information of all employees in the R & D department, i.e. salary grade
select e.*,s.grade
from emp e,dept d,salgrade s
where (e.dept_id=d.id) and (d.name=' R & D department ') and (e.salary between s.losal and s.hisal);
7. Query the average salary of employees in the R & D department
select avg(e.salary)
from emp e, dept d
where e.dept_id=d.id and d.name=' R & D department ';
8. Query the information of employees whose wages are higher than extinction
select *
from emp
where emp.salary > (
select e.salary
from emp e
where e.name=' extinction '
);
9. Query employee information with higher than average salary
select *
from emp
where salary> (
select avg(e.salary)
from emp e
);
10. Query the information of employees whose salary is lower than the average salary of the Department
select *
from emp
where emp.salary<(
select avg(salary)
from emp e
where e.dept_id=emp.dept_id
);
11. Check all department information , And count the number of employees in the Department
select d.*, (
select count(*)
from emp
where emp.dept_id=d.id
)
from dept d;
边栏推荐
猜你喜欢
[Charles' daily problems] when you open Charles, you can't use nails
IO stream - file - properties
数组的子集不能累加出的最小正数
2022-07-28:以下go语言代码输出什么?A:AA;B:AB;C:BA;D:BB。 package main import ( “fmt“ ) func main() { f
WPF 界面布局必知基础
DM data guard cluster setup
win11系统错误:由于找不到 iertutil.dll,无法继续执行代码。重新安装程序可能会解决此问题
MySQL----多表查询
Nodejs安装教程
Kubernetes (五) ---------部署 Kubernetes Dashboard
随机推荐
Sword finger offer II 115: reconstruction sequence
ERROR 1045 (28000) Access denied for user ‘root‘@‘localhost‘解决方法
2D cartoon rendering - advanced skills
Connecting PHP 7.4 to Oracle configuration on Windows
Redis基础篇
MySQL 高级(进阶) SQL 语句 (一)
Idea cannot find a database solution
Dbasql interview questions
Flink实时仓库-DWD层(处理复杂数据-流和表的装换处理)模板代码
vagrant box 集群 处理
Can MySQL export tables regularly?
Teacher Wu Enda's machine learning course notes 02 univariate linear regression
微信小程序的反编译
buck电路boot电容短路和断路实测波形
Teacher Wu Enda's machine learning course notes 00 are written in the front
Implementation of DDP cluster distributed training under pytoch multi GPU conditions (brief introduction - from scratch)
使用VsCode配置MySQL实现连接、查询、等功能
WPF 界面布局必知基础
【Redis】Redis开发规范与注意事项
vim文本编辑器的一些使用小技巧