MySQL database - multi-table operation

insert image description here

foreword

In daily database use, the data we process is not just a single table, but requires us to process data in multiple tables at the same time, so today I will share with you about the multi-table operation of MySQL.

multi-table relationship

Before learning multi-table operations, we need to know what multi-table relationships are: one-to-one relationship, one-to-many relationship/many-to-one relationship, many-to-many relationship.

one-to-one relationship

A one-to-one relationship means that one record in one table can only correspond to one record in another table, and they are associated through a common primary key or unique key.

insert image description here

One-to-many/many-to-one relationships

A multi-table one-to-many or many-to-one relationship means that one record in one table can correspond to multiple records in another table, and they are associated through a common primary key or foreign key.
insert image description here

many-to-many relationship

A multi-table many-to-many relationship means that two or more tables are related to each other, and the records of each table can correspond to multiple records of other tables. A common way to deal with multi-table many-to-many relationships is to use intermediate tables (association tables) to join the relationships.

insert image description here

foreign key constraints

A MySQL foreign key constraint is a database constraint used to ensure the integrity of relationships between tables. It defines that the value of a field or a group of fields in one table must be consistent with the value in another table, or meet certain conditions.

A foreign key constraint associates a field of one table (called a foreign key) with a primary or unique key of another table (called a referential key) by specifying a foreign key relationship. In this way, if the foreign key value in a table changes, MySQL will automatically check whether there is a matching key value in the reference table to maintain data consistency.

Foreign key constraints have the following effects:

  1. Enforce referential integrity: Foreign key constraints ensure that data in a table exists in the associated table at the time of the reference.
  2. Maintain data consistency: Foreign key constraints prevent inconsistent results when data is deleted or modified in related tables.
  3. Provides query optimization: The MySQL optimizer can use foreign key relationships to speed up query operations.
  4. Cascading operations: Foreign key constraints can define cascading operations. When data in the reference table is updated or deleted, corresponding operations are automatically performed on the data in the associated table.

MySQL foreign key constraints have the following characteristics:

  1. Enforce referential integrity: foreign key constraints ensure that the data in the referencing table exists in the referenced table, preventing invalid references. This ensures data consistency and integrity.

  2. Automatically verify and maintain relationships: MySQL will automatically verify and maintain foreign key constraints to ensure that associated data is updated, inserted or deleted correctly. If the foreign key constraint is violated, MySQL will report an error and refuse to perform the operation.

  3. Support cascading operations: Foreign key constraints can define cascading operations. When deleting or updating operations in the reference table, corresponding operations are automatically performed on the related data in the associated table. For example, cascading deletion can be implemented, and when data in the reference table is deleted, related data in the associated table is deleted at the same time.

  4. Optimize query performance: The MySQL optimizer can use foreign key constraints to optimize query operations. By correctly setting the foreign key relationship, MySQL can perform JOIN operations more efficiently and improve query performance.

  5. Can be disabled and enabled: When required, foreign key constraints can be disabled or enabled to allow certain operations that require a temporary violation of the foreign key constraint. This feature is useful in some situations, but needs to be used with caution to prevent data inconsistencies.

  6. Reliance on Data Integrity: Using foreign key constraints allows data integrity to be maintained at the database level rather than depending on the application. This reduces the chance of errors and data inconsistencies, making the database more reliable.

Create foreign key constraints

There are two ways for MySQL to create foreign key constraints: 1. Create foreign key constraints when creating tables: create table 表名(列名1 类型,列名2 类型,constraint 外键名 foreign key(列名) references 主表(主表列名);2. Create foreign key constraints after creating tables:alter table 表名 add constraint 外键名 foreign key(列名) referrnces 主表(主表列名);

The premise of adding foreign key constraints after creating a table is: the data in the foreign key column in the secondary table must be consistent with the data in the primary key column in the main table or there is no data.

Create foreign key constraints when creating tables

create table class(class_id int primary key,name varchar(10)); -- 主表
insert into class values(1,'高三1班'), 
						(2,'高三2班'),
						(3,'高三3班');
												
create table student
			(class_id int,student_id int,name varchar(20),gender varchar(10),
			constraint student_fk foreign key(class_id) 
			references class(class_id));

insert image description here

Add foreign key constraints after table creation

create table class(class_id int primary key,name varchar(10)); -- 主表
insert into class values(1,'高三1班'), 
						(2,'高三2班'),
						(3,'高三3班');

create table student
	(class_id int,student_id int,name varchar(20),gender varchar(10));
	
alter table student 
add constraint student_fk 
foreign key(class_id) references class(class_id);

insert image description here

insert data

When we insert data, if we insert data into the main table first, we don’t need to pay attention to anything, but when we insert data into the slave table, we need to pay attention: the data of the foreign key column of the inserted record is in the main table Whether the primary key column of the table exists, if it exists, the insertion is successful, otherwise, the insertion fails. So suggest:When inserting data, first insert data into the master table, and then insert data into the slave table.

insert into student values(1,2301,'张三','男');

insert image description here

insert into student values(4,2302,'王五','男');

insert image description here

What if the data already exists in the table when we create a new foreign key constraint?

create table student
	(class_id int,student_id int,name varchar(20),gender varchar(10));
	
insert into student values(1,2301,'张三','男'),
						(3,2302,'王五','男');
-- 我们插入的数据都是与主键列中的数据相对应
	
alter table student 
add constraint student_fk 
foreign key(class_id) references class(class_id);

insert image description here
The foreign key column of the above data corresponds to the data in the primary key column, so the insertion is successful.

create table student
	(class_id int,student_id int,name varchar(20),gender varchar(10));
	
insert into student values(1,2301,'张三','男'),
						(4,2302,'王五','男');
-- 这里class_id 4 在主键列中并不存在,我们看看是否能
alter table student 
add constraint student_fk 
foreign key(class_id) references class(class_id);

insert image description here
Here class_id 4 does not exist in the primary key column, so the insert fails.

Delete data from tables with foreign key constraints

What if we need to delete data in a table with foreign key constraints?

  • Delete data from the table can be deleted at will
  • When we delete the data in the main table, we need to pay attention: when the primary key column of the record we deleted is still dependent on the foreign key column, it cannot be deleted.

insert image description here
insert image description here
At this time, the primary key column 1 is still dependent on the foreign key column, let's try to delete it.

delete from class where class_id = 1;

insert image description here
The deletion failed, so when we delete the data in the main table, we need to consider whether the primary key column of the record is still dependent on the foreign key column.When deleting data, it is recommended to delete the data in the secondary table first, and then delete the undependent data in the main table

Remove foreign key constraints

But when we don't need foreign key constraints, we can also delete foreign key constraints.alter table 表名 drop foreign key 外键名;

insert image description here
At this point the foreign key constraint has been dropped.

Multi-table joint query

Multi-table query is the most important and most used operation in MySQL operation, so we need to learn MySQL multi-table query operation well.

MySQL multi-table query refers to the process of obtaining joint data by specifying the connection conditions (association conditions) between tables involving multiple tables in one query statement. Multi-table queries can be used to retrieve, filter and combine data from multiple tables.

MySQL multi-table operations mainly include:

  • cross join query
  • inner join query
    • Implicit inner join (SQL92 standard)
    • Explicit inner joins (SQL99 standard)
  • outer join
    • left outer join
    • right outer join
    • full outer join
  • subquery
  • self-association query

And we are implementing query operations, and foreign key constraints will not affect multi-table queries.

data preparation

We prepare data for subsequent multi-table queries.

use mydb3;
-- 创建部门表
create table if not exists dept3(
  deptno varchar(20) primary key ,  -- 部门号
  name varchar(20) -- 部门名字
);

-- 创建员工表
create table if not exists emp3(
  eid varchar(20) primary key , -- 员工编号
  ename varchar(20), -- 员工名字
  age int,  -- 员工年龄
  dept_id varchar(20)  -- 员工所属部门
);

-- 给dept3表添加数据
insert into dept3 values('1001','研发部');
insert into dept3 values('1002','销售部');
insert into dept3 values('1003','财务部');
insert into dept3 values('1004','人事部');

-- 给emp3表添加数据
insert into emp3 values('1','乔峰',20, '1001');
insert into emp3 values('2','段誉',21, '1001');
insert into emp3 values('3','虚竹',23, '1001');
insert into emp3 values('4','阿紫',18, '1001');
insert into emp3 values('5','扫地僧',85, '1002');
insert into emp3 values('6','李秋水',33, '1002');
insert into emp3 values('7','鸠摩智',50, '1002'); 
insert into emp3 values('8','天山童姥',60, '1003');
insert into emp3 values('9','慕容博',58, '1003');
insert into emp3 values('10','丁春秋',71, '1005');

insert image description here
insert image description here

cross join query

MySQL cross join query (Cross
Join) is a query method used to return all possible combinations from two or more tables. It returns all combinations of each row of the left table with each row of the right table without using any join conditions. Therefore, a cross join query produces a result set with the number of rows equal to the number of rows in the left table times the number of rows in the right table

select * from 表1,表2
insert image description here
Cross join query is actually performed between multiple tablesCartesian Product

insert image description here
After Cartesian product of two tables with m and n records respectively, there will be m*n records.

select * from dept3,emp3;

insert image description here
But when we see the data of the table after the Cartesian product, we will find that there are many unsuitable records, so we also need to filter the table generated by the Cartesian product.

inner join query

MySQL inner join query (Inner Join) is a query method used to return a record set that meets the join condition from two or more tables. An inner join matches rows from two tables based on specified join conditions and returns the matching rows.

Inner join is the most commonly used connection type, which can help us establish an association relationship between multiple tables and obtain related data. The result set of an inner join contains only matching rows, so data can be associated and filtered based on join conditions to provide more specific and meaningful results.

Implicit inner connection: select * from 表A,表B where 条件;
Explicit inner connection: select * from 表A inner join B on 条件;inner can be omitted.

MySQL also supports more than two tables for multi-table operations:select * from 表A join B on 条件 join C on 条件...;

insert image description here
insert image description here

implicit inner join

select * from dept3,emp3 where dept3.deptno = emp3.dept_id;
-- 如果两张表的列相同,可使用 表名.列名 来区分

insert image description here
explicit inner join

select * from dept3 inner join emp3 on dept3.deptno = emp3.dept_id;

insert image description here

Outer join query

MySQL Outer Join (Outer
Join) is a query method used to return records that satisfy the join condition and some or all of the records that do not meet the join condition from two or more tables. Outer joins can help us get the relationship between the main table and the joined table and include unmatched rows.

Outer join queries are divided into:

  • left outer join query
  • right outer join query
  • full outer join query

left outer join query

MySQL Left Outer Join query (Left Outer
Join) is a query method to obtain related data between tables by returning all rows from the left table (main table) and matching rows of the right table (join table) that meet the join condition. A left outer join keeps all rows from the left table, even if there are no matching rows in the right table.

A left outer join joins each row from the left table with a matching row from the right table and returns a matching result set. Returns a NULL value if there is no matching row in the right table.

select * from 表A left outer join 表B on 条件;
insert image description here

select * from dept3 left outer join emp3 on dept3.deptno = emp3.dept_id;

insert image description here

Here, because the personnel department has no employees, but because it is a left outer connection, all the data in the left table should be displayed, so the data in the personnel department is filled with NULL.

right outer join query

MySQL Right Outer Join query (Right Outer Join) is a query method to obtain related data between tables by returning all rows from the right table (join table) and the matching rows of the left table (main table) that meet the join conditions. A right outer join retains all rows from the right table, even if there are no matching rows in the left table.

A right outer join joins each row from the right table with a matching row from the left table and returns a matching result set. Returns NULL if there is no matching row in the left table.

select * from 表A right outer join 表B on 条件;

insert image description here

select * from dept3 right outer join emp3 on dept3.deptno = emp3.dept_id;

insert image description here
1005 has no corresponding department, so fill it with NULL.

The left outer join can realize the conversion between two tables by exchanging positions.

select * from emp3 left outer join dept3 on dept3.deptno = emp3.dept_id;

full outer join query

Full outer join is a query method that returns all rows in the left table and right table at the same time, as well as matching rows that satisfy the join condition. It is able to get all the data from the left and right tables and relate them.

The full outer join is actually splicing the data of the right outer join under the data of the left outer join or splicing the data of the left outer join under the data of the right outer join.

But MySQL does not support full outer joins full outer join, we can use unionto achieve full outer joins. And unionthere are two ways of full outer connection: 左外连接 union 右外连接;to remove the full outer connection, 左外连接 union all 右外连接;and not to remove the full outer connection.

insert image description here
insert image description here

deduplicated full outer join

select * from dept3 left outer join emp3 on dept3.deptno = emp3.dept_id
union
select * from dept3 right outer join emp3 on dept3.deptno = emp3.dept_id;

insert image description here
Do not deduplicate outer joins

select * from dept3 left outer join emp3 on dept3.deptno = emp3.dept_id
union all
select * from dept3 right outer join emp3 on dept3.deptno = emp3.dept_id;

insert image description here

subquery

MySQL subquery (Subquery) refers to nesting another complete SQL query in one SQL query. A subquery can contain clauses such as SELECT, FROM, WHERE, etc. like a normal query, and can return a result set that can be used directly in the outer query.

Subqueries are often used to decompose complex queries into smaller, manageable query blocks, and to achieve more flexible and precise query purposes through nesting. It can be nested in SELECT, FROM, WHERE, etc. clauses to filter, sort, calculate and join data.

There are four types of data that can be returned by a subquery:

  1. Single column and single row: Returns the content of a specific column, which can be understood as a single-value data.
  2. Single row and multiple columns: returns the contents of multiple columns in a row of data
  3. Multiple rows and multiple columns: Return the content of the same column in multiple rows of records, which is equivalent to giving an operation range.
  4. Multiple rows and multiple columns: The result returned by the query is a temporary table.

If we need to know who is in a certain department, do we need to know the department number represented by this department first, because the department number is stored in the employee information table, and we can find out who is there after knowing the department number.

-- 查询销售部有哪些人
select deptno from dept3 where name = '销售部';

insert image description here
After we know the department number, we find out the information of the person whose department number is 1002 in the employee table.

select ename from emp3 where dept_id = 1002;

insert image description here
Because select deptno from dept3 where name = '销售部';the result of is 1002, we can directly nest this query into select ename from emp3 where dept_id = 1002;, that isselect ename from emp3 where dept_id = (select deptno from dept3 where name = '销售部');

select ename from emp3 
where dept_id = (select deptno from dept3 where name = '销售部'); -- 返回单行单列

insert image description here

Query the information of R&D and sales personnel.

select eid,ename from emp3 
where dept_id 
in (select deptno from dept3 where name in ('研发部','销售部'));

insert image description here

-- 查询研发部30岁以下的员工信息,包括员工号,员工名字,部门名字
select eid,ename,name from (select * from emp3 where age < 30) t1
join (select * from dept3 where name = '研发部') t2
on t1.dept_id = t2.deptno;

Because the final requirement is to display the employee number, employee name, and department name, these data are in two tables, so we need to combine the two tables and make a judgment on the data in each table.

insert image description here

subquery keyword

There are some commonly used logical keywords in subqueries:

  • ALL keyword
  • ANY keyword
  • SOME keyword
  • IN keyword
  • EXISTS keyword

ALL keyword

In MySQL, the keyword ALL can be used in a subquery to compare the results returned by the subquery with the outer query conditions.

When the keyword ALL is used in conjunction with a subquery, it means that the outer query condition must be compared with all the values ​​returned by the subquery, and only when the outer query condition is greater than or less than all the values ​​​​in the subquery, the condition is considered satisfied.

select ... from ... where c > all(查询语句);

-- 查询员工表中年龄大于1003部门所有员工的年龄的信息
select * from emp3 where age > all(select age from emp3 where dept_id = 1003);

insert image description here

-- 查询不属于任何部门的员工的信息
select * from emp3 where dept_id != all(select deptno from dept3);

insert image description here

ANY and SOME keywords

In MySQL, the ANY and SOME keywords can be used with subqueries to compare the outer query condition with any value in the result set returned by the subquery.

The functions of these two keywords are similar, and they both indicate that the external query condition only needs to match any value in the result set returned by the subquery to judge that the condition is met.

select ... from ... where c > any/some(查询语句);

-- 查询年龄大于1003部门任何一个员工的员工信息
select * from emp3 where age > any(select age from emp3 where dept_id = 1003);

insert image description here

IN keyword

The IN keyword is used to check whether the outer query condition matches any value in the subquery result set. An outer query condition is considered satisfied if it matches a value in the subquery result set.

select ... from ... where c in(查询语句);

-- 查询部门为研发部和销售部的员工的信息
select * from emp3 
where dept_id 
in (select deptno from dept3 where name = '研发部' or name = '销售部');

insert image description here

EXISTS keyword

The EXISTS keyword is used to determine whether the subquery has a result. If there is a result, it is considered to meet the condition, and the previous query statement will be executed. If the subquery has no result, it is considered not to meet the condition, and the previous query will not be executed.

select ... from ... where exists(查询语句);

Suppose we want to query the information of employees whose age is older than 60.

-- 查询年龄大于60岁的员工信息
select * from emp3 where exists (select * from emp3 where age > 60);

insert image description here
You will find that the information of all employees is displayed here, why is this? Because in the subquery behind EXISTS, the search object is the entire table of emp3, so each query has results, so all the information in emp3 is printed, so what should we do?

We can visualize the query process of MySQL as a record-by-record screening, so we can use the table alias, and then use the table alias to determine whether the age of the employee in each record is greater than 60.

-- 查询年龄大于60岁的员工信息
select * from emp3 t where exists (select * from emp3 where t.age > 60);

insert image description here

In most situations where exists can also be used, but we recommend using exists, because the underlying exists of MySQL has been optimized, and the query efficiency is higher.

self-association query

MySQL self-association query refers to using the same table for join operation in the query to create a virtual association. In a self-associated query, you can treat the table as two or more distinct tables and refer to them in the query.

Self-associated queries typically involve using table aliases in queries so that different instances of the same table can be referenced. In this way, an association relationship can be established by comparing the column with itself.

Self-association queries are very useful when processing data with hierarchical structures, relationship chains, etc. Common application scenarios include obtaining management hierarchical relationships, finding related records, and obtaining kinship relationships.

MySQL self-query must use an alias, otherwise an error will occur

We prepare some data for autocorrelation.

create table t_sanguo(
	eid int primary key,
	ename varchar(20),
	manager_id int,
	foreign key (manager_id) references t_sanguo (eid));
	
	insert into t_sanguo values(1,'刘协',NULL),
								(2,'刘备',1),
								(3,'关羽',2),
								(4,'张飞',2),
								(5,'曹操',1),
								(6,'许褚',5),
								(7,'典韦',1),
								(8,'孙权',1),
								(9,'周瑜',8),
								(10,'鲁肃',8);

We need to display the superior information corresponding to each person.

select t1.ename,t2.ename manager 
from t_sanguo t1 join t_sanguo t2 
on t1.manager_id = t2.eid; 

insert image description here
We should also display Liu Xie's superior information, so we use the left outer join.

select t1.ename,t2.ename manager 
from t_sanguo t1 left join t_sanguo t2 
on t1.manager_id = t2.eid; 

insert image description here

Guess you like

Origin blog.csdn.net/m0_73888323/article/details/131967773