Foreword:
Multi-table query refers to the use of multiple tables in one SQL statement for data query and manipulation. Multi-table query can query the relationship between data tables, for example, you can obtain more complete data information by connecting multiple tables. We have also introduced about single-table query, which has been compiled into an article and published: [MySQL Database | Article 9] DQL Operation_I am a blog of beef-CSDN blog
Table of contents
Classification of multi-table queries:
Multi-table relationship:
- one-to-many
- many to many
- one to one
1. One-to-many:
Example: the relationship between departments and employees, one department corresponds to multiple employees, and one employee corresponds to one department.
Implementation: Create a foreign key on the many side, pointing to the primary key on the one side.
Illustration:
2. Many to many:
Example: the relationship between students and courses, a student can choose multiple courses, and one course can also be selected by multiple students.
Implementation: Create the third table in the middle, which contains at least two foreign keys in the middle, and associates the two primary keys respectively
Graphic: Example:
Implement the relationship between students and courses in a many-to-many relationship
Student table:
curriculum:
Student Course Relationship Table:
We set both studentid and courseid as two foreign keys, which are connected to the class schedule and student table respectively. This way we have a many-to-many relationship.
We can use the view tool that comes with datagrip to make a more intuitive graph:
3. One to one:
Example: Relationship between users and user details
Relationship: The one-to-one relationship is mostly used for the splitting of a single table.
Implementation: add a foreign key to either side, associate the primary key of the other side, and set the foreign key to be unique.
After splitting:
We can view the relationship between the user basic information table and the user education information table in the visualization tool provided by datagrip:
Multi-table query:
Multi-table query refers to the use of multiple tables in one SQL statement for data query and manipulation. Multi-table query can query the relationship between data tables, for example, you can obtain more complete data information by connecting multiple tables.
For the convenience of demonstration, we first insert two tables: dept table and emp table
dept table:
emp table:
If you just directly query two tables together:
select *from emp ,dept;
search result:
We found that this kind of query is too time-consuming, because it is to match each person to the six positions, which is really not conducive to our direct observation. This phenomenon (every element in A must be combined with an element in B) is called the Cartesian product phenomenon.
And we need to eliminate this redundant Cartesian product phenomenon in the actual multi-table query, so that the data can be presented in the most intuitive and clear way.
The correct idea should be that we add a judgment condition: only when the personnel position id in the empt table is equal to the dept position id, then output.
code:
select * from emp,dept where dept_id=dept.id;
result:
At this point we have successfully eliminated the redundant Cartesian product.
Classification of multi-table queries:
Connection query:
Inner join:
It is equivalent to querying the intersection data of A and B.
Outer join:
Left outer join: query all the data in the left table, and the intersection data of the two tables
Right outer join: query all the data in the right table, and the intersection data of the two tables
Self join:
The connection query between the current table and itself, the self-join must use the table alias
Joint query:
Combine the results of multiple queries to form a new query result
subquery:
A SQL statement nests another SQL statement, and the nested SQL statement is called a subquery.
Inner join:
1. Implicit inner connection:
SELECT 字段列表 FROM 表1,表2,WHERE 条件;
2. Explicit inner join:
SELECT 字段列表 FROM 表1 [INNER] JOIN 表2 ON 连接条件;
Case:
1. Query the name of each employee and the name of the associated department (implicit inner connection)
select emp.name,dept.name from emp,dept where emp.dept_id=dept.id;
result:
2. Query the name of each employee and the name of the associated department (explicit inner join)
select emp.name,dept.name from emp join dept on emp.dept_id = dept.id;
result:
Outer join:
Left outer join:
select 字段名 from 表1 left [outer] join 表2 on 条件;
Right outer join:
select 字段名 from 表1 right [outer] join 表2 on 条件;
We consider Table 1 to be the left table and Table 2 to be the right table:
Diagram:
Case:
1. Query all information in emp and the department information corresponding to its personnel (left outer connection)
select emp.* ,d.name from emp left join dept d on d.id = emp.dept_id;
result
2. Query all the data in the dept table and the corresponding employee names (right outer join)
select dept.*,e.name from dept right join emp e on dept.id = e.dept_id;
result:
Self join:
select 字段列表 from 表A 别名A join 表A 别名B on 条件;
A self-join query can be an inner join query or an outer join query.
the case
1. Query the names of employees and their leaders (inner connection):
select a.name ,b.name from emp a,emp b where a.managerid=b.id;
Result: (We can see that Jin Yong, who has no boss here, is not displayed, because he does not belong to the intersection of the two tables)
2. Query the names of the employees and their leaders (outer join), even if the employees have no leaders, they should also be included:
select a.name,d.name from emp a left join emp d on a.managerid=d.id;
Result: (Jin Yong without a boss is also printed at this time)
Joint query:
SELECT 字段列表 FROM 表A....
UNION [ALL]
SELECT 字段列表 FROM 表B....
The ALL keyword determines whether to deduplicate, if you do not want to deduplicate, do not write ALL.
case:
1. Query all employees whose salary is greater than 5000 and employees whose age is greater than 50
select name from emp where emp.salary>5000
union
select name from emp where emp.age>50;
result:
Points to note: For a joint query, the two query fields to be merged must have the same type and the same number of columns.
subquery:
SELECT *FROM T1 WHERE COLUMN1 =(SELECT COLUMN1 FROM T2);
According to the different types of subqueries, we divide them into
- Scalar subquery (subquery result is a single value)
- Column subquery (subquery result is a column)
- row subquery (subquery result is one row)
- Table subquery (the result of the subquery is multiple rows and multiple columns)
The red arrow points to the subquery
Scalar subquery:
the result returned by the subquery is a single value (string, date, number, etc.)
Common operators: = <> > >= < <=
In the following cases, the subquery returns a single value: id, entrydate, so it is called a scalar subquery.
case:
1. Query all employee information of the 'sales department' (first query the number of the sales department, and then query whose job number meets the requirements)
select * from emp where dept_id=(select id from dept where name ='销售部');
result:
2. Query employee information after joining 'Fang Dongbai'
select * from emp where entrydate>(select entrydate from emp where name='方东白');
result:
Column subquery:
The result returned by the subquery is a column (can be multiple rows). This subquery is called a column subquery
Commonly used operators: IN , NOT IN , ANY , SOME , ALL
Case:
1. Query all employee information of sales department and marketing department
select * from emp where dept_id in (select id from dept where name ='销售部'or name ='市场部');
result:
2. Query information about personnel whose salary is higher than that of everyone in the finance department
select * from emp where salary>all (select salary from emp where dept_id = (select id from dept where name ='财务部'));
result:
Row subquery:
The result returned by the subquery is a row (can be multiple columns), this subquery is a row subquery
Commonly used operators: = , <> , IN, NOT IN
case:
1. Query the same employee information as Zhang Wuji's salary and leadership
select * from emp where (salary,managerid)=(select salary,managerid from emp where name ='张无忌')
result:
Table subquery:
The return result of a subquery is multiple rows and multiple columns. This kind of subquery result is called a table subquery.
Most commonly used operator: IN
Case:
1. Query the employee information with the same position and salary as Luzhangke and Song Yuanqiao:
select * from emp where (job,salary) in (select job,salary from emp where name='鹿杖客' or name ='宋远桥');
result:
Summarize:
Multi-table query refers to operating multiple tables in one SQL statement at the same time, and querying the association between different tables to obtain richer and more accurate data. Common methods of multi-table query include inner join, left join, right join and full join. Multi-table query is widely used in practical operations, which can meet the complex data query and processing requirements, and can also improve the query efficiency and performance of the database.
This is the end of today's content, thank you for reading.
If my content is helpful to you, please like, comment and bookmark . Creation is not easy, everyone's support is my motivation to persevere!