Database MySQL - multi-table query

Table of contents

1. Multi-table relationship

1. One-to-many (many-to-one) relationship

2. Many-to-many relationship

3. One-to-one relationship

 2. Overview of multi-table query

1 Overview

2. Classification

3. Inner connection

4. Outer connection

5. Self-connection

6. Joint query-union

Seven, sub query

1. Scalar subqueries

2. Column query

3. Row subqueries

4. Table subquery


1. Multi-table relationship

In project development, when designing the data table structure, the table structure will be analyzed and designed according to the business requirements and the relationship between the business sectors. Since the businesses are related to each other, there are also various table structures. There are basically three types of connections:

  1. One-to-many (many-to-one)
  2. many to many
  3. one to one

1. One-to-many (many-to-one) relationship

  • Case: the relationship between departments and employees
  • Relationship: One department corresponds to multiple employees, and one employee corresponds to one department
  • Realization: Create a foreign key on the many side, pointing to the primary key on the one side

2. Many-to-many relationship

  • Case: Student-Course Relationship
  • Relationship: A student can take multiple courses, and a course can also provide multiple student choices 
  • Implementation: Create a third intermediate table, the intermediate table contains at least two foreign keys, which are associated with the primary keys of the two parties

create table student_course(
    id int auto_increment comment '主键' primary key ,
    studentid int not null comment '学生id',
    courseid int not null comment '课程id',
    constraint fk_courseid foreign key (courseid) references course(id),
    constraint fk_studentid foreign key (studentid) references student(id)
)comment '学生课程中间表';

3. One-to-one relationship

  • Case: Relationship between users and user details
  • Relationship: One-to-one relationship, mostly used for single-label splitting, put the basic fields of one table in one table, and put other detailed fields in another table to improve operational efficiency
  • Realization: Add a foreign key to any party, associate the primary key of the other party, and set the foreign key to be unique (UNIQUE)

 2. Overview of multi-table query

1 Overview

  • Overview: Refers to querying data from multiple tables
  • Cartesian product: Cartesian product refers to all combinations of two sets A and B in mathematics. ( In multi-table query, invalid Cartesian products need to be eliminated )
-- 单表查询
select * from emp;
-- 多表查询
select * from emp,dept;
-- 查询结果为两张表所有组合情况

-- 消除笛卡尔积
-- 加入where条件
select * from emp,dept where emp.dept_id = dept.id;

2. Classification

① Connection query

  • Inner join: It is equivalent to querying the intersection data of two tables 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

② Sub link

3. Inner connection

Inner join: It is equivalent to querying the intersection data of two tables A and B.

Inner join query syntax:

  • Implicit inner join: SELECT field list FROM table 1, table 2 WHERE  condition... ;
  • Explicit inner connection: SELECT field list FROM table 1 [ INNER ] JOIN table 2 ON connection condition....;
-- 内连接展示
-- 表结构:emp、dept
-- 连接条件: emp.dept_id = dept.id

-- 1. 查询每一个员工的姓名,以及关联的部门名称(隐式内连接)
select emp.name,dept.name from emp,dept where emp.dept_id = dept.id;
-- 表明起别名
select e.name,d.name from emp e,dept d where e.dept_id = d.id;
-- 2. 查询每一个员工的姓名,以及管理的部门名称(显式内连接)
select e.name,d.name from emp e inner join dept d on e.dept_id = d.id;
-- inner 关键字可省略
select e.name,d.name from emp e join dept d on e.dept_id = d.id;

4. Outer connection

left outer join
  1. Based on the left table, match the data in the right table, and if it matches, display the matched data.
  2. If no match is found, the data in the left table will be displayed normally, and the data in the right table will be displayed as NULL.
right outer join
  1. The right table is used as the benchmark, and the data in the left table is matched. If it matches, the matched data is displayed.
  2. If no match is found, the data in the right table will be displayed normally, and the data in the left table will be displayed as NULL.

Outer join query syntax:

  • Left outer join: SELECT field list FROM table 1 LEFT [ OUTER ] JOIN table 2 ON condition... ;
  • Right outer join: SELECT field list FROM table 1 RIGHT [ OUTER ] JOIN table 2 ON condition... ;
-- 外连接展示
-- 1. 查询emp表中所有数据 ,和对应的部门信息(左外连接)
select e.*,d.name from emp e left join dept d on d.id = e.dept_id;
-- 2. 查询dept表中所有信息 ,和对应的员工信息(右外连接)
select d.*,e.name from dept d right join emp e on d.id = e.dept_id;

5. Self-connection

A self-join query can be an inner join query or an outer join query.

Self-join query syntax: SELECT field list FROM table A alias A JOIN table A alias B ON condition... ;

-- 自连接展示
-- 1. 查询员工 及其 所属领导的名字
-- 表结构: emp
-- 必须要起别名 否则不能分清主次表
select a.name,b.name from emp a,emp b where a.managerid = b.id;

-- 2. 查询所有的员工 emp 及其领导的名字 emp,如果员工没有领导,也需要查询出来(左外)
-- 表结构:emp a , emp b
select a.name '员工',b.name '领导' from emp a left join emp b on a.managerid = b.id;

6. Joint query-union

For union queries, the results of multiple queries are combined to form a new query result set.

grammar:

         SELECT field list FROM table A...

          UNION [ ALL

         SELECT field list FROM table B ...;

-- union , union all
-- 1. 将薪资低于 5000 的员工 , 和 年龄大于 50岁 的员工全部查询出来
-- union 合并去重
-- union all 直接合并
select * from emp where salary < 5000
union 
select * from emp where age > 50;

Notice:

  • For the joint query, the number of columns and field types of multiple tables must be consistent.
  • union all will directly merge all the data together, and union will deduplicate the merged data.

Seven, sub query

Concept: nested SELECT statements in SQL statements become nested queries, also known as subqueries.

语法:SELECT * FROM t1 WHERE column1 = ( SELECT column1 FROM t2 ) ;

The syntax outside the subquery can be any of INSERT / UPDATE / DELETE / SELECT .

① According to the subquery structure, it is divided into:

  • Scalar subquery (subquery result is a single value)
  • Column subquery (the result of the subquery is a column)
  • Row subquery (subquery result is one row)
  • Table subquery (the result of the subquery is multiple rows and multiple columns)

② According to the position of the subquery, it is divided into: after WHERE, after FROM, after SELECT

1. Scalar subqueries

  • A subquery returns a single value (number, string, date, etc.), and in its simplest form, such a subquery is called a scalar subquery .
  • Commonly used operators: = <> > >= < <=
-- 标量子查询
-- 1. 查询 “销售部” 所有员工信息
--     a.查询 “销售部” 部门id
select id from dept where name = '销售部';
--     b.根据“销售部”部门id 查询员工信息
select * from emp where dept_id = 4;
-- 整合
select * from emp where dept_id = (select id from dept where name = '销售部');

-- 2. 查询在 “方东白” 入职之后的员工信息
--      a.查询 “房东白” 的入职日期
select entrydate from emp where name = '方东白';
--      b. 查询在指定日期之后入职的成员信息
select * from emp where entrydate > '20090-02-12';
-- 整合
select * from emp where entrydate > (select entrydate from emp where name = '方东白');

2. Column query

  • The result returned by a subquery is a column (can be multiple rows), this subquery is called a column subquery .
  • Common operators: IN, NOT IN, ANY, SOME, ALL
    operator describe
    IN Within the specified collection range, choose one more
    NOT IN is not within the specified collection range
    ANY In the list returned by the subquery, any one can satisfy
    SOME Equivalent to ANY, ANY can be used wherever SOME is used
    ALL All values ​​in the list returned by the subquery must satisfy
    -- 列子查询
    -- 1. 查询 “销售部” 和 “市场部” 的所有员工信息
    --     a.查询 “销售部” 和 “市场部” 的部门id
    select id from dept where name = '销售部' or  name = '市场部';
    --     b.根据部门id 查询员工信息
    select * from emp where dept_id in (2,4);
    -- 整合
    select * from emp where dept_id in (select id from dept where name = '销售部' or  name = '市场部');
    -- 2. 查询比财务部所有员工工资高的员工信息
    --     a.查询 “财务部” 人员工资
    select id from dept where name = '财务部';
    select salary from emp where dept_id = (select id from dept where name = '财务部');
    --     b.查询 比财务部所有员工工资高的员工
    select * from emp where salary > all ();
    -- 整合
    select * from emp where salary > all 
    (select salary from emp where dept_id = (select id from dept where name = '财务部'));
    
    -- 3. 查询比研究部其中任意一个人工资高的员工信息
    --     a.查询 “研发部” 人员工资
    select salary from emp where dept_id = (select id from dept where name = '研发部');
    --     b.查询 比研究部其中任意一个人工资高的员工
    select * from emp where salary > any 
    (select salary from emp where dept_id = (select id from dept where name = '研发部'));

3. Row subqueries

  • The result returned by a subquery is a row (can be multiple columns), this subquery is called a row subquery .
  • Commonly used operators: = , <> , IN , NOT IN
-- 行子查询
-- 1. 查询与 “张无忌” 的薪资 及 直属领导相同的员工信息
--     a.查询 “张无忌” 的薪资 及 直属领导
select salary,managerid from emp where name = '张无忌';
--     b.查询与 “张无忌” 的薪资 及 直属领导相同的员工信息
select * from emp where salary = 12500 and managerid = 1;
-- 整合
select * from emp where (salary,managerid) = (select * from emp where salary = 12500 and managerid = 1);

4. Table subquery

  • The result returned by a subquery is multiple rows and multiple columns. This kind of subquery is called a table subquery .
  • Commonly used operators: IN
-- 表子查询
-- 1. 查询与 “鹿杖客” ,“宋远桥” 的职位和薪资相同的员工信息
--     a.查询 “鹿杖客”  “宋远桥”的的职位和薪资
select job,salary from emp where name = '鹿杖客' or name = '宋远桥';
--     b.查询与 “鹿杖客” ,“宋远桥” 的职位和薪资相同的员工信息
select * from emp where (job,salary) in (select job,salary from emp where name = '鹿杖客' or name = '宋远桥');
-- 2. 查询入职日期 是 “2006-01-01”之后的员工信息,及其部门信息
--     a.查询入职日期 是 “2006-01-01”之后的员工信息
select * from emp where entrydate > '2006-01-01';
--     b.查询对应的部门信息
select e.*,d.* from (select * from emp where entrydate > '2006-01-01') e left join dept d on e.dept_id = e.id;

Guess you like

Origin blog.csdn.net/hdakj22/article/details/129727599
Recommended