MySQL multi-table query (super detailed)

1. Multi-table relationship

        During project development, when designing the database table structure, the table structure will be analyzed and designed based on business needs and the relationship between business modules. Since businesses are interrelated, there are various connections between each table structure. Basically there are three types:

  • One-to-many (many-to-one)
  • many to many
  • One to one

1.1 One-to-many

Case: Department and employee
Relationship: One department corresponds to multiple employees, and one employee corresponds to one department.
Implementation: Establish a foreign key on the many side, pointing to the primary key of the one side (in development, the setting of foreign keys is generally cancelled, that is, on the many side One party can create a field that points to the primary key of one party)

1.2 Many-to-many

Case: Students and courses
Relationship: A student can choose multiple courses, and one course can also be taken by multiple students. Implementation
: Create a third intermediate table. The intermediate table contains at least two foreign keys, which are related to the primary keys of the two parties (development In general, you can cancel the setting of foreign keys, that is, create two fields in the intermediate table pointing to the primary keys of both parties)

1.3 One-on-one

Case: User and user details
Relationship: One-to-one relationship, mostly used for single table splitting. Put the basic fields of a table in one table and other detail fields in another table to improve operational efficiency. Implementation: on either
side Add a foreign key, associate it with the primary key of the other party, and set the foreign key to be unique (UNIQUE) (During development, the setting of the foreign key is generally canceled, that is, adding a field on either party to associate the primary key of the other party)

2. Multi-table query-Cartesian product

Combined query (Cartesian product, all combined results will be displayed):
  select * from employee, dept;

Cartesian product: all combinations of two sets A and B (in multi-table queries, invalid Cartesian products need to be eliminated)

Eliminate invalid Cartesian products:
  select * from employee, dept where employee.dept_id = dept.id;

3. Multi-table query-inner join

The inner join queries the intersection of the two tables.

Implicit inner join:
  SELECT 字段列表 FROM 表1, 表2 WHERE 条件 ...;

Explicit inner join:
  SELECT 字段列表 FROM 表1 [ INNER ] JOIN 表2 ON 连接条件 ...;

example:

  1. -- 查询员工姓名,及关联的部门的名称
  2. -- 隐式
  3. select e.name, d.name from employee as e, dept as d where e.dept = d.id;
  4. -- 显式
  5. select e.name, d.name from employee as e inner join dept as d on e.dept = d.id;

4. Multi-table query-outer join (left outer join, right outer join)

Left outer join:
     Query all the data in the left table, and the intersection data of the two tables,
  SELECT 字段列表 FROM 表1 LEFT [ OUTER ] JOIN 表2 ON 条件 ...;
     which is equivalent to querying all the data in table 1, including the intersection data of table 1 and table 2.

Right outer join:
     Query all data in the right table and some data at the intersection of the two tables
  SELECT 字段列表 FROM 表1 RIGHT [ OUTER ] JOIN 表2 ON 条件 ...;

example:

  1. -- 左
  2. select e.*, d.name from employee as e left join dept as d on e.dept = d.id;
  3. select d.name, e.* from dept d left join emp e on e.dept = d.id; -- 这条语句与下面的语句效果一样
  4. -- 右
  5. select d.name, e.* from employee as e right join dept as d on e.dept = d.id;

5. Multi-table query-self-join

Query the connection between the current table and itself. Table aliases must be used for self-joins.

grammar:
  SELECT 字段列表 FROM 表A 别名A JOIN 表A 别名B ON 条件 ...;

     Self-join query, which can be an inner join query or an outer join query.

example:

  1. -- 查询员工及其所属领导的名字
  2. select a.name, b.name from employee a, employee b where a.manager = b.id;
  3. -- 没有领导的也查询出来
  4. select a.name, b.name from employee a left join employee b on a.manager = b.id;

6. Multi-table query-joint query

Combine the results of multiple queries to form a new query set

grammar:

    SELECT 字段列表 FROM 表A ...

    UNION [ALL]

    SELECT 字段列表 FROM 表B ...

Precautions

  • UNION ALL will have duplicate results, UNION will not
  • Union query is more efficient than using or and will not invalidate the index.
  • For joint queries, the number of columns in multiple tables must be consistent, and the field types must also be consistent.

Here is an example showing how to use a union query to get data from two tables:

SELECT column1, column2 FROM table1 UNION SELECT column3, column4 FROM table2;

In the above example, SELECT column1, column2 FROM table1and SELECT column3, column4 FROM table2are two independent SELECTstatements that obtain specific column data from table1the and tables respectively. table2By merging them using UNIONoperators, you can get a result set containing data from both tables. (Generally speaking, table1 and table2 of the joint query are the same table. For example, if you query the employee table for employees with a salary greater than 5,000 or employees with an age greater than 40, you can use a joint query)

It should be noted that UNIONwhen using a joint query, the SELECTnumber of columns, column names and data types of the two statements must match. If you need to retain duplicate rows, use UNION ALLinstead UNION.

7. Multi-table query-subquery (nested query)

Nesting a SELECT statement in an SQL statement is called a nested query, also known as a subquery.
SELECT * FROM t1 WHERE column1 = ( SELECT column1 FROM t2);
The statement outside the subquery can be any of INSERT / UPDATE / DELETE / SELECT

According to the subquery results, they can be divided into:

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

According to the subquery position, it can be divided into:

  • After WHERE
  • FROM after
  • After SELECT

7.1 Scalar subquery

 The result returned by a subquery is a single value (number, string, date, etc.).
Commonly used operators: - < > > >= < <=

example:

  1. -- 查询销售部所有员工
  2. select id from dept where name = '销售部';
  3. -- 根据销售部部门ID,查询员工信息
  4. select * from employee where dept = 4;
  5. -- 合并(子查询)
  6. select * from employee where dept = (select id from dept where name = '销售部');
  7. -- 查询xxx入职之后的员工信息
  8. select * from employee where entrydate > (select entrydate from employee where name = 'xxx');

7.2 List subquery

 The result returned is a column (can be multiple rows).

Commonly used operators:

Operator describe
IN Within the specified collection range, select one from more than one
NOT IN Not within the specified collection range
ANY In the list returned by the subquery, any one of them can be satisfied
SOME Same as ANY, ANY can be used wherever SOME is used.
ALL All values ​​in the list returned by the subquery must satisfy

example: 

  1. -- 查询销售部和市场部的所有员工信息
  2. select * from employee where dept in (select id from dept where name = '销售部' or name = '市场部');
  3. -- 查询比财务部所有人工资都高的员工信息
  4. select * from employee where salary > all(select salary from employee where dept = (select id from dept where name = '财务部'));
  5. -- 查询比研发部任意一人工资高的员工信息
  6. select * from employee where salary > any (select salary from employee where dept = (select id from dept where name = '研发部'));

7.3 Row subquery

The result returned is a row (can be multiple columns).
Common operators: =, <, >, IN, NOT IN

example:

  1. -- 查询与xxx的薪资及直属领导相同的员工信息
  2. select * from employee where (salary, manager) = (12500, 1);
  3. select * from employee where (salary, manager) = (select salary, manager from employee where name = 'xxx');

7.4 Table subquery

The returned result is multiple rows and multiple columns.
Common operators: IN

example:

  1. -- 查询与xxx1,xxx2的职位和薪资相同的员工
  2. select * from employee where (job, salary) in (select job, salary from employee where name = 'xxx1' or name = 'xxx2');
  3. -- 查询入职日期是2006-01-01之后的员工,及其部门信息
  4. select e.*, d.* from (select * from employee where entrydate > '2006-01-01') as e left join dept as d on e.dept = d.id;

Guess you like

Origin blog.csdn.net/weixin_55772633/article/details/132121779