MySQL basics - multi-table query

This article introduces MySQL's multi-table query

multi-table relationship

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

one-to-many

Case: department and employee
Relationship: one department corresponds to multiple employees, one employee corresponds to one department
Realization: establish a foreign key on the multi-party, and point to the primary key on the one-party

many to many

Case: Student and Course
Relationship: One student can choose multiple courses, and one course can also be taken by multiple students. Implementation
: Create a third intermediate table, which contains at least two foreign keys, and associates the two primary keys respectively

one to one

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

Inquire

Overview: Query 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)

inner join

The inner join query is the intersection of two tables

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

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

Explicit performance is higher than implicit

grammar:

#隐式内连接
SELECT 字段列表 FROM 表列表 WHERE 条件...;

#显式内连接
SELECT 字段列表 FROM 表1 [INNER] JOIN 表2 ON 连接条件;

Example:

#查询每一个员工的姓名,以及关联的部门名称(隐式)
SELECT emp.name,dept.name FROM emp,dept WHERE emp.dept_id = dept.id;

#查询每一个员工的姓名,以及关联的部门名称(显示)
SELECT e.name,d.name FROM emp e INNER JOIN dept d ON e.dept_id = d.id;

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 in the intersection of two tables
SELECT 字段列表 FROM 表1 RIGHT [ OUTER ] JOIN 表2 ON 条件 ...;

Example:

#查询emp表的所有数据,和对应的部门信息(左外连接)
SELECT * FROM emp e LEFT OUTER JOIN dept d ON e.dept_id = d.id;

#查询dept表的所有数据,和对应的员工信息(右外连接)
SELECT d.*,e.* FROM emp e RIGHT OUTER JOIN dept d ON e.dept_id = d.id;

self-join

The connection query between the current table and itself, the self-join must use the table alias

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:

#查询员工及其直属领导的名字
SELECT e1.name 员工,e2.name 领导 FROM emp e1 JOIN emp e2 ON e1.managerid = e2.id;

#查询所有员工emp及其领导的名字emp,如果没有领导也要查询出来
SELECT e1.*,e2.name 领导 FROM emp e1 LEFT JOIN emp e2 ON e1.managerid = e2.id;

joint query

Merge the results of multiple queries to form a new query set
Syntax:

SELECT 字段列表 FROM 表A ...
UNION [ALL]
SELECT 字段列表 FROM 表B ...

Precautions:

  • UNION ALL will have duplicate results, UNION will not
  • Joint query is more efficient than using or and will not invalidate the index

Example:

#将薪资低于5000的员工,和年龄大于50岁的员工都查询出来。
SELECT * FROM emp WHERE salary < 5000 UNION SELECT * FROM emp WHERE age > 50 ORDER BY id ASC;
  • For the joint query, the number of columns of multiple tables must be consistent, and the field types must also be consistent
  • UNION ALL will directly merge the two result sets, while UNION will deduplicate

subquery

Nested SELECT statements in SQL statements are called nested queries, also known as subqueries .
SELECT * FROM t1 WHERE column1 = ( SELECT column1 FROM t2);
The statement outside the subquery can be INSERT / UPDATE / DELETE / SELECTany of

According to the subquery results can be 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 can be divided into:

  • after WHERE
  • after FROM
  • after SELECT

scalar subqueries

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

Example:

#查询销售部的所有员工信息
SELECT * FROM emp  WHERE dept_id = (SELECT id FROM dept WHERE name = '销售部');

#查询方东白之后入职的员工信息
SELECT * FROM emp WHERE entrydate > (SELECT entrydate FROM emp WHERE name = '方东白');

#查询xxx入职之后的员工信息
select * from employee where entrydate > (select entrydate from employee where name = 'xxx');

column query

The result returned by a subquery is a column (can be multiple rows), this subquery is called a column subquery

Commonly used operators: IN、NOT IN、ANT、SOME、ALL
insert image description here
Examples:

-- 查询销售部和市场部的所有员工信息
select * from employee where dept in (select id from dept where name = '销售部' or name = '市场部');

-- 查询比财务部所有人工资都高的员工信息
select * from employee where salary > all(select salary from employee where dept = (select id from dept where name = '财务部'));

-- 查询比研发部任意一人工资高的员工信息
select * from employee where salary > any (select salary from employee where dept = (select id from dept where name = '研发部'));

row subquery

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

example:

#查询与张无忌的薪资及直属领导都相同的员工
SELECT * FROM emp WHERE salary = (SELECT salary FROM emp WHERE name = '张无忌') AND managerid = (SELECT managerid FROM emp WHERE name = '张无忌');

#或
SELECT * FROM emp WHERE (salary,managerid) = (SELECT salary,managerid FROM emp WHERE name = '张无忌');

table subquery

The returned result is multi-row and multi-column
Common operators:IN

example:

#查询与鹿杖客、宋远桥的职位和薪资相同的员工信息

SELECT * FROM emp WHERE job IN (SELECT job FROM emp WHERE name = '鹿杖客' OR name = '宋远桥') AND salary IN (SELECT salary FROM emp WHERE name = '鹿杖客' OR name = '宋远桥');

#查询入职日期是2006-01-01之后的员工信息,及部门信息
SELECT e.*,d.name FROM emp e LEFT JOIN dept d ON e.dept_id = d.id WHERE e.entrydate > '2006-01-01';

Multi-table query case

#查询员工的姓名、年龄、职位、部门信息
SELECT e.name,e.age,e.job,d.name FROM emp e LEFT JOIN dept d ON e.dept_id = d.id;

#查询年龄小于30岁的员工姓名、年龄、职位、部门信息
SELECT e.name,e.age,e.job,d.name FROM emp e LEFT JOIN dept d ON e.dept_id = d.id WHERE age < 30;

#查询拥有员工的部门ID、部门名称
SELECT d.* FROM dept d WHERE d.id IN (SELECT e.dept_id FROM emp e);

#查询所有年龄大于40的员工,及其归属的部门名称;如果员工没有分配部门,也需要展示出来
SELECT e.name,d.name FROM emp e LEFT JOIN dept d ON e.dept_id = d.id WHERE e.age > 40;

#查询所有员工的工资等级
SELECT e.name,s.grade FROM emp e,salgrade s WHERE e.salary >s.losal AND e.salary <s.hisal;

#查询研发部所有员工的信息及工资等级
SELECT e.name,s.grade FROM emp e,salgrade s WHERE e.salary >s.losal AND e.salary <s.hisal AND e.dept_id = 1;

#查询研发部员工的平均工资
SELECT AVG(salary) FROM emp WHERE dept_id = 1;

#查询工资比灭绝高的员工信息
SELECT * FROM emp WHERE salary > (SELECT salary FROM emp WHERE name = '灭绝');

#查询比平均工资高的员工信息
SELECT * FROM emp WHERE salary > (SELECT AVG(salary) FROM emp);

#查询比本部门平均工资低的员工信息
SELECT * FROM emp e2 WHERE e2.salary < (SELECT AVG(e1.salary) FROM emp e1 WHERE e1.dept_id = e2.dept_id);

#查询所有的部门信息,并统计部门的员工人数
SELECT d.id,d.name,(SELECT COUNT(*) FROM emp e WHERE e.dept_id = d.id) 人数 FROM dept d;

Guess you like

Origin blog.csdn.net/baidu_33256174/article/details/130671530