MySQL study notes 06 [multi-table query, sub-query, multi-table query exercises]

  • MySQL Document-Dark Horse Programmer (Tencent Weiyun): https://share.weiyun.com/RaCdIwas
  • 1-MySQL foundation.pdf, 2-MySQL constraints and design.pdf, 3-MySQL multi-table query and transaction operation.pdf
  1. MySQL study notes 01 [database concept, MySQL installation and use] [day01]
  2. MySQL study notes 02 [SQL basic concepts and general grammar, database CRUD operations] [day01]
  3. MySQL study notes 03 [CRUD operations of database tables, basic operations recorded in database tables, client-side graphical interface tool SQLyog] [day01]

  4. MySQL study notes 04 [database query operations, table constraints] [day01, day02]

  5. MySQL study notes 05 [multi-table operation, three paradigms, database backup and restore] [day02]

  6. MySQL study notes 06 [multi-table query, sub-query, multi-table query exercises] [day03]

  7. MySQL study notes 07 [transaction, user management and authority management] [day03]

table of Contents

12 Multi-table query

Today's content

Multi-table query_overview

* Prepare sql

Multi-table query_inner join

Implicit inner join

Explicit inner join

Multi-table query_outer join

Left outer join

Right outer join

13 subqueries

Multi-table query_subquery overview

Multi-table query_subquery case 1 & case 2

Multi-table query_subquery situation 3

14 Multi-table query exercise

Multi-table query_exercise 1

Create database db3, create 4 data tables

Demand 1

Demand 2

Multi-table query_exercise 2

Demand 3

Demand 4

Multi-table query_exercise 3

Demand 5

Demand 6


12 Multi-table query

Today's content

  1. Multi-table query
  2. Affairs
  3. DCL

Multi-table query_overview

* Query syntax:
    select
        column name list
    from
        table name list
    where....
* Prepare sql

    ...

* Cartesian product:
    * There are two sets A, B, take all the components of these two sets.
    * To complete multi-table query, you need to eliminate useless data.
* Classification of multi-table query:
    1. Inner join query

    2. Outer join query

    3. Subqueries

* Prepare sql

# 创建部门表
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);

Multi-table query_inner join

    1. Inner join query:
         1. Implicit inner join: use the where condition to eliminate useless data.
            * Example:
            - Query all employee information and corresponding department information

            SELECT * FROM emp, dept WHERE emp.`dept_id` = dept.`id`;
            
            - Query the name and gender of the employee table. The name of the department table
            SELECT emp.name, emp.gender, dept.name FROM emp, dept WHERE emp.`dept_id` = dept.`id`;
            
            SELECT 
                t1.name, - the name of the employee table
                t1.gender, - The gender of the employee table
                t2.name - the name of the department table
            FROM
                emp t1,
                dept t2
            WHERE 
                t1.`dept_id` = t2.`id`;

        2. Explicit inner join:
            * Syntax: select field list from table name 1 [inner] join table name 2 on condition
            * For example:
                * SELECT * FROM emp INNER JOIN dept ON emp.`dept_id` = dept.`id`;    
                * SELECT * FROM emp JOIN dept ON emp.`dept_id` = dept.`id`;    

        3. Inner join query (notes):
            1. From which tables to query data
            2. What are the conditions
            3. Which fields to query

Implicit inner join

Explicit inner join

Multi-table query_outer join

    2. Outer link query:
         1. Left outer join:
            * Syntax: select field list from table 1 left [outer] join table 2 on condition;
            * The query is all the data in the left table and its intersection.
            * Example:
                - Query all employee information, if the employee has a department, query the department name, if there is no department, the department name will not be displayed
                SELECT t1.*,t2.`name` FROM emp t1 LEFT JOIN dept t2 ON t1.`dept_id `= t2.`id`;
         2. Right outer join:
            * Syntax: select field list from table 1 right [outer] join table 2 on condition;
            * The query is all data in the right table and its intersection.
            * Example:
                SELECT * FROM dept t2 RIGHT JOIN emp t1 ON t1.`dept_id` = t2.`id`;

Left outer join

Right outer join

13 subqueries

Multi-table query_subquery overview

    3. Subquery:
        * Concept: Nested query in query, called nested query as subquery.
            - Query the information of the employee with the
            highest salary - 1 Query the highest salary 9000
            SELECT MAX(salary) FROM emp;
            
            - 2 Query the employee information and the salary is equal to 9000
            SELECT * FROM emp WHERE emp.`salary` = 9000 ;
            
            - One sql completes this operation. Subquery
            SELECT * FROM emp WHERE emp.`salary` = (SELECT MAX(salary) FROM emp);

  

Multi-table query_subquery case 1 & case 2

    3. Subqueries:
        * Different situations
            of subqueries 1. The results of subqueries are single row and single column:
                * Subqueries can be used as conditions, using operators to determine. Operator:> >= <<= =
                * 
                - Query people whose salary is less than the average salary
                SELECT * FROM emp WHERE emp.salary <(SELECT AVG(salary) FROM emp);
            2. The result of the subquery is multiple rows and single columns :
                * Sub-query can be used as a condition, use the operator in to judge
                - query all employee information of
                the'finance department' and'marketing department' SELECT id FROM dept WHERE NAME ='finance department' OR NAME ='marketing department';
                SELECT * FROM emp WHERE dept_id = 3 OR dept_id = 2;
                - Subquery
                SELECT * FROM emp WHERE dept_id IN (SELECT id FROM dept WHERE NAME ='Finance Department' OR NAME ='Marketing Department');

Multi-table query_subquery situation 3

            3. The result of the subquery is multi-row and multi-column:
                * The subquery can be used as a virtual table to participate in the query
                - query the employee information and department information after the entry date of 2011-11-11
                - subquery
                SELECT * FROM dept t1 ,(SELECT * FROM emp WHERE emp.`join_date`> '2011-11-11') t2
                WHERE t1.id = t2.dept_id;
                
                - Ordinary inner join
                SELECT * FROM emp t1, dept t2 WHERE t1. `dept_id` = t2.`id` AND t1.`join_date`> '2011-11-11';

14 Multi-table query exercise

Multi-table query_exercise 1

Create database db3, create 4 data tables

  

-- 部门表
CREATE TABLE dept (
  id INT PRIMARY KEY PRIMARY KEY, -- 部门id
  dname VARCHAR(50), -- 部门名称
  loc VARCHAR(50) -- 部门所在地
);

-- 添加4个部门
INSERT INTO dept(id,dname,loc) VALUES 
(10,'教研部','北京'),
(20,'学工部','上海'),
(30,'销售部','广州'),
(40,'财务部','深圳');



-- 职务表,职务名称,职务描述
CREATE TABLE job (
  id INT PRIMARY KEY,
  jname VARCHAR(20),
  description VARCHAR(50)
);

-- 添加4个职务
INSERT INTO job (id, jname, description) VALUES
(1, '董事长', '管理整个公司,接单'),
(2, '经理', '管理部门员工'),
(3, '销售员', '向客人推销产品'),
(4, '文员', '使用办公软件');



-- 员工表
CREATE TABLE emp (
  id INT PRIMARY KEY, -- 员工id
  ename VARCHAR(50), -- 员工姓名
  job_id INT, -- 职务id
  mgr INT , -- 上级领导
  joindate DATE, -- 入职日期
  salary DECIMAL(7,2), -- 工资
  bonus DECIMAL(7,2), -- 奖金
  dept_id INT, -- 所在部门编号
  CONSTRAINT emp_jobid_ref_job_id_fk FOREIGN KEY (job_id) REFERENCES job (id),
  CONSTRAINT emp_deptid_ref_dept_id_fk FOREIGN KEY (dept_id) REFERENCES dept (id)
);

-- 添加员工
INSERT INTO emp(id,ename,job_id,mgr,joindate,salary,bonus,dept_id) VALUES 
(1001,'孙悟空',4,1004,'2000-12-17','8000.00',NULL,20),
(1002,'卢俊义',3,1006,'2001-02-20','16000.00','3000.00',30),
(1003,'林冲',3,1006,'2001-02-22','12500.00','5000.00',30),
(1004,'唐僧',2,1009,'2001-04-02','29750.00',NULL,20),
(1005,'李逵',4,1006,'2001-09-28','12500.00','14000.00',30),
(1006,'宋江',2,1009,'2001-05-01','28500.00',NULL,30),
(1007,'刘备',2,1009,'2001-09-01','24500.00',NULL,10),
(1008,'猪八戒',4,1004,'2007-04-19','30000.00',NULL,20),
(1009,'罗贯中',1,NULL,'2001-11-17','50000.00',NULL,10),
(1010,'吴用',3,1006,'2001-09-08','15000.00','0.00',30),
(1011,'沙僧',4,1004,'2007-05-23','11000.00',NULL,20),
(1012,'李逵',4,1006,'2001-12-03','9500.00',NULL,30),
(1013,'小白龙',4,1004,'2001-12-03','30000.00',NULL,20),
(1014,'关羽',4,1007,'2002-01-23','13000.00',NULL,10);



-- 工资等级表
CREATE TABLE salarygrade (
  grade INT PRIMARY KEY,   -- 级别
  losalary INT,  -- 最低工资
  hisalary INT -- 最高工资
);

-- 添加5个工资等级
INSERT INTO salarygrade(grade,losalary,hisalary) VALUES 
(1,7000,12000),
(2,12010,14000),
(3,14010,20000),
(4,20010,30000),
(5,30010,99990);



-- 需求:

-- 1.查询所有员工信息。查询员工编号,员工姓名,工资,职务名称,职务描述

-- 2.查询员工编号,员工姓名,工资,职务名称,职务描述,部门名称,部门位置
   
-- 3.查询员工姓名,工资,工资等级

-- 4.查询员工姓名,工资,职务名称,职务描述,部门名称,部门位置,工资等级

-- 5.查询出部门编号、部门名称、部门位置、部门人数
 
-- 6.查询所有员工的姓名及其直接上级的姓名,没有领导的员工也需要查询

Demand 1

- 1. Query all employee information: query employee number, employee name, salary, job title, job description.

analysis:

  1. Employee number, employee name, salary, need to query emp table. Job name, job description need to query job table
  2. Query condition emp.job_id = job.id

SELECT 
    t1.`id`, - employee number
    t1.`ename`, - employee name
    t1.`salary`, - salary
    t2.`jname`, - job title
    t2.`description` - job description
FROM 
    emp t1, job t2
WHERE 
    t1.`job_id` = t2.`id`;

Demand 2

- 2. Query employee number, employee name, salary, job title, job description, department name, department location.

analysis:

  1. Employee number, employee name, salary emp job title, job description job department name, department location dept
  2. 条件: emp.job_id = job.id and emp.dept_id = dept.id

SELECT 
    t1.`id`, - employee number
    t1.`ename`, - employee name
    t1.`salary`, - salary
    t2.`jname`, - job title
    t2.`description`, - job description
    t3.`dname`, - department name
    t3.`loc` - department location
FROM 
    emp t1, job t2, dept t3
WHERE 
    t1.`job_id` = t2.`id` AND t1.`dept_id` = t3.` id`;

Multi-table query_exercise 2

Demand 3

- 3. Query the employee's name, salary, salary grade.

analysis:

  1. Employee name, salary emp salary grade salarygrade
  2. 条件 emp.salary >= salarygrade.losalary and emp.salary <= salarygrade.hisalary / emp.salary BETWEEN salarygrade.losalary and salarygrade.hisalary

SELECT 
    t1.ename ,
    t1.`salary`,
    t2.*
FROM emp t1, salarygrade t2
WHERE t1.`salary` BETWEEN t2.`losalary` AND t2.`hisalary`;

Demand 4

- 4. Query employee name, salary, job title, job description, department name, department location, salary grade.

analysis:

  1. Employee name, salary emp, job title, job description job department name, department location, dept salary grade salarygrade
  2. 条件: emp.job_id = job.id and emp.dept_id = dept.id and emp.salary BETWEEN salarygrade.losalary and salarygrade.hisalary

SELECT
    t1.`ename`,
    t1.`salary`,
    t2.`jname`,
    t2.`description`,
    t3.`dname`,
    t3.`loc`,
    t4.`grade`
FROM
    emp t1,job t2,dept t3,salarygrade t4
WHERE
    t1.`job_id` = t2.`id` 
    AND t1.`dept_id` = t3.`id`
    AND t1.`salary` BETWEEN t4.`losalary` AND t4.`hisalary`;

Multi-table query_exercise 3

Demand 5

- 5. Query the department number, department name, department location, and department number.

analysis:

  1. Department number, department name, department location dept table. Department number emp table
  2. Use group queries. Complete grouping according to emp.dept_id, query count(id)
  3. Use a subquery to associate the query result of step 2 with the dept table

SELECT 
    t1.`id`,
    t1.`dname`,
    t1.`loc`,
    t2.total
FROM
    dept t1,
    (SELECT
        dept_id,COUNT(id) total -- 别名total
    FROM
        emp
    GROUP BY dept_id) t2
WHERE t1.`id` = t2.dept_id;

  

Demand 6

- 6. Query the names of all employees and the names of their immediate superiors. Employees without a leader also need to query.

analysis:

  1. Name emp, the name of the immediate superior emp * The id and mgr of the emp table are self-associated
  2. Condition emp.id = emp.mgr
  3. Query all the data in the left table, and the intersection data * Use the left outer join query

SELECT
    t1.ename,
    t1.mgr,
    t2.`id`,
    t2.ename
FROM emp t1, emp t2
WHERE t1.mgr = t2.`id`;

SELECT
    t1.ename,
    t1.mgr,
    t2.`id`,
    t2.`ename`
FROM emp t1
LEFT JOIN emp t2
ON t1.`mgr` = t2.`id`;

  

Traditional Chinese Medicine: The kidneys lead to the brain! Kidney essence and metaplasia brain! The kidney controls the bone, the bone produces the marrow, and the brain is the sea of ​​marrow.

Guess you like

Origin blog.csdn.net/weixin_44949135/article/details/113664166