MySQL多表查询

Posted fqh202

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL多表查询相关的知识,希望对你有一定的参考价值。

一、准备表

#建表
create table dept(
id int primary key not null auto_increment,
name varchar(20) not null
);

create table employee(
id int primary key auto_increment,
name varchar(20) not null,
sex enum(‘male‘,‘female‘) not null default ‘male‘,
age int not null ,
dept_id int not null,
foreign key(dept_id) references dept(id)
on delete cascade
on update cascade
);

#插入数据
insert into dept(name) values
(‘技术‘),
(‘人力资源‘),
(‘销售‘),
(‘运营‘);

insert into employee(name,sex,age,dept_id) values
(‘egon‘,‘male‘,18,1),
(‘alex‘,‘female‘,48,2),
(‘wupeiqi‘,‘male‘,38,3),
(‘yuanhao‘,‘female‘,28,4),
(‘liwenzhou‘,‘male‘,18,1),
(‘jingliyang‘,‘female‘,18,3)
;


#查看表结构和数据
mysql> desc department;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(11) | YES | | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+

mysql> desc employee;
+---------+-----------------------+------+-----+---------+----------------+
| Field   | Type                  | Null | Key | Default | Extra          |
+---------+-----------------------+------+-----+---------+----------------+
| id      | int(11)               | NO   | PRI | NULL    | auto_increment |
| name    | varchar(20)           | NO   |     | NULL    |                |
| sex     | enum(‘male‘,‘female‘) | NO   |     | male    |                |
| age     | int(11)               | NO   |     | NULL    |                |
| dept_id | int(11)               | NO   | MUL | NULL    |                |
+---------+-----------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)


mysql> select * from dept;
+----+----------+
| id | name     |
+----+----------+
|  1 | 技术     |
|  2 | 人力资源 |
|  3 | 销售     |
|  4 | 运营     |
+----+----------+
4 rows in set (0.00 sec)


mysql> select * from employee;
+----+------------+--------+-----+---------+
| id | name       | sex    | age | dept_id |
+----+------------+--------+-----+---------+
|  1 | egon       | male   |  18 |       1 |
|  2 | alex       | female |  48 |       2 |
|  3 | wupeiqi    | male   |  38 |       3 |
|  4 | yuanhao    | female |  28 |       4 |
|  5 | liwenzhou  | male   |  18 |       1 |
|  6 | jingliyang | female |  18 |       3 |
+----+------------+--------+-----+---------+
6 rows in set (0.00 sec)

表department与employee

二、多表连接查询

重点:外链接语法
SELECT 字段列表
    FROM 表1 INNER|LEFT|RIGHT JOIN 表2
    ON 表1.字段 = 表2.字段;
  1. 交叉连接:不适用任何匹配条件。生成笛卡尔积,结果没有任何参考作用;
mysql> select * from dept, employee;
+----+----------+----+------------+--------+-----+---------+
| id | name     | id | name       | sex    | age | dept_id |
+----+----------+----+------------+--------+-----+---------+
|  1 | 技术     |  1 | egon       | male   |  18 |       1 |
|  2 | 人力资源 |  1 | egon       | male   |  18 |       1 |
|  3 | 销售     |  1 | egon       | male   |  18 |       1 |
|  4 | 运营     |  1 | egon       | male   |  18 |       1 |
|  1 | 技术     |  2 | alex       | female |  48 |       2 |
|  2 | 人力资源 |  2 | alex       | female |  48 |       2 |
|  3 | 销售     |  2 | alex       | female |  48 |       2 |
|  4 | 运营     |  2 | alex       | female |  48 |       2 |
|  1 | 技术     |  3 | wupeiqi    | male   |  38 |       3 |
|  2 | 人力资源 |  3 | wupeiqi    | male   |  38 |       3 |
|  3 | 销售     |  3 | wupeiqi    | male   |  38 |       3 |
|  4 | 运营     |  3 | wupeiqi    | male   |  38 |       3 |
|  1 | 技术     |  4 | yuanhao    | female |  28 |       4 |
|  2 | 人力资源 |  4 | yuanhao    | female |  28 |       4 |
|  3 | 销售     |  4 | yuanhao    | female |  28 |       4 |
|  4 | 运营     |  4 | yuanhao    | female |  28 |       4 |
|  1 | 技术     |  5 | liwenzhou  | male   |  18 |       1 |
|  2 | 人力资源 |  5 | liwenzhou  | male   |  18 |       1 |
|  3 | 销售     |  5 | liwenzhou  | male   |  18 |       1 |
|  4 | 运营     |  5 | liwenzhou  | male   |  18 |       1 |
|  1 | 技术     |  6 | jingliyang | female |  18 |       3 |
|  2 | 人力资源 |  6 | jingliyang | female |  18 |       3 |
|  3 | 销售     |  6 | jingliyang | female |  18 |       3 |
|  4 | 运营     |  6 | jingliyang | female |  18 |       3 |
+----+----------+----+------------+--------+-----+---------+
24 rows in set (0.00 sec)

  1. 内连接
# 按照where条件取出两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了正确的结果
mysql> select * from dept, employee where dept.id = employee.dept_id;
# 效率较低,连表操作最好还是用inner jion;

#找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了正确的结果
#department没有204这个部门,因而employee表中关于204这条员工信息没有匹配出来
mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee inner join department on employee.dep_id=department.id; 
+----+-----------+------+--------+--------------+
| id | name      | age  | sex    | name         |
+----+-----------+------+--------+--------------+
|  1 | egon      |   18 | male   | 技术         |
|  2 | alex      |   48 | female | 人力资源     |
|  3 | wupeiqi   |   38 | male   | 人力资源     |
|  4 | yuanhao   |   28 | female | 销售         |
|  5 | liwenzhou |   18 | male   | 技术         |
+----+-----------+------+--------+--------------+

#上述sql等同于
mysql> select employee.id,employee.name,employee.age,employee.sex,department.name from employee,department where employee.dep_id=department.id;

+----+----------+----+------------+--------+-----+---------+
| id | name     | id | name       | sex    | age | dept_id |
+----+----------+----+------------+--------+-----+---------+
|  1 | 技术     |  1 | egon       | male   |  18 |       1 |
|  1 | 技术     |  5 | liwenzhou  | male   |  18 |       1 |
|  2 | 人力资源 |  2 | alex       | female |  48 |       2 |
|  3 | 销售     |  3 | wupeiqi    | male   |  38 |       3 |
|  3 | 销售     |  6 | jingliyang | female |  18 |       3 |
|  4 | 运营     |  4 | yuanhao    | female |  28 |       4 |
+----+----------+----+------------+--------+-----+---------+
  1. 外链接之左连接:优先显示左表全部记录
# 以左表为准,即找出所有员工信息,当然包括没有部门的员工
# 本质就是:在内连接的基础上增加左边有右边没有的结果
mysql> select employee.id, employee.name, employee.age, dept.name as dept
    -> from employee right join dept
    -> on employee.dept_id = dept.id;
+------+------------+------+----------+
| id   | name       | age  | dept     |
+------+------------+------+----------+
|    1 | egon       |   18 | 技术     |
|    5 | liwenzhou  |   18 | 技术     |
|    2 | alex       |   48 | 人力资源 |
|    3 | wupeiqi    |   38 | 销售     |
|    6 | jingliyang |   18 | 销售     |
|    4 | yuanhao    |   28 | 运营     |
+------+------------+------+----------+
6 rows in set (0.00 sec)
  1. 外链接之右连接:优先显示右表全部记录
#以右表为准,即找出所有部门信息,包括没有员工的部门
#本质就是:在内连接的基础上增加右边有左边没有的结果
mysql> select employee.id,employee.name,dept.name as dept_name from employee right join dept on employee.dept_id=dept.id;
+------+------------+-----------+
| id   | name       | dept_name |
+------+------------+-----------+
|    1 | egon       | 技术      |
|    5 | liwenzhou  | 技术      |
|    2 | alex       | 人力资源  |
|    3 | wupeiqi    | 销售      |
|    6 | jingliyang | 销售      |
|    4 | yuanhao    | 运营      |
| NULL | NULL       | 支持      |
+------+------------+-----------+
7 rows in set (0.00 sec)
  1. 全外连接:显示左右两个表全部记录
全外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果
#注意:mysql不支持全外连接 full JOIN
#强调:mysql可以使用此种方式间接实现全外连接
select * from employee left join dept on employee.dept_id = dept.id
union
select * from employee right join dept on employee.dep_id = dept.id
;
#查看结果

# 也包括没有员工的部门或不属于已知部门的员工;
mysql> select * from employee left join dept on employee.dept_id = dept.id union select * from employee right join dept on employee.dept_id = dept.id ;
+------+------------+--------+------+---------+------+----------+
| id   | name       | sex    | age  | dept_id | id   | name     |
+------+------------+--------+------+---------+------+----------+
|    1 | egon       | male   |   18 |       1 |    1 | 技术     |
|    5 | liwenzhou  | male   |   18 |       1 |    1 | 技术     |
|    2 | alex       | female |   48 |       2 |    2 | 人力资源 |
|    3 | wupeiqi    | male   |   38 |       3 |    3 | 销售     |
|    6 | jingliyang | female |   18 |       3 |    3 | 销售     |
|    4 | yuanhao    | female |   28 |       4 |    4 | 运营     |
| NULL | NULL       | NULL   | NULL |    NULL |    5 | 支持     |
+------+------------+--------+------+---------+------+----------+
7 rows in set (0.00 sec)

三、符合条件连接查询

#示例1:以内连接的方式查询employee和dept表,并且employee表中的age字段值必须大于25,即找出年龄大于25岁的员工以及员工所在的部门

mysql> select employee.id, employee.name as "员工", employee.age, dept.name as ‘部门‘ from employee right join dept
    -> on employee.dept_id = dept.id
    -> where age > 25 order by age;
+------+---------+------+----------+
| id   | 员工    | age  | 部门     |
+------+---------+------+----------+
|    2 | alex    |   48 | 人力资源 |
|    3 | wupeiqi |   38 | 销售     |
|    4 | yuanhao |   28 | 运营     |
+------+---------+------+----------+
3 rows in set (0.00 sec)

四、子查询

#1:子查询是将一个查询语句嵌套在另一个查询语句中。
#2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。
#3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字
#4:还可以包含比较运算符:= 、 !=、> 、<等
  1. 带IN关键字的子查询
# 查询平均年龄在25岁以上的部门名
select id,name from dept
    where id in 
        (select dept_id from emp group by dept_id having avg(age) > 25);

# 查看技术部员工姓名
# 1. 找出技术部门的id;2.根据提供的部门id在员工表中查询符合条件的员工;
select name from emp
    where dept_id in 
        (select id from dept where name=‘技术‘);

# 查看不足1人的部门名(子查询得到的是有人的部门id)
# 1.不足一人的部门id;2.根据id找到部门名称
mysql> select name from dept where id in (select dept_id as dept_num from emp group by dept_id having count(id) <=1);
+----------+
| name     |
+----------+
| 人力资源 |
| 运营     |
+----------+
2 rows in set (0.00 sec)
  1. 带比较运算符的子查询
# 比较运算符:=、!=、>、>=、<、<=、<>
# 查询大于所有人平均年龄的员工的姓名与年龄
# 1、平均年龄; 2、在表中根据条件查询
mysql> select name, age from emp where age>(select avg(age) from emp);
+---------+-----+
| name    | age |
+---------+-----+
| alex    |  48 |
| wupeiqi |  38 |
+---------+-----+
2 rows in set (0.00 sec)


# 查询大于部门内平均年龄的员工姓名、年龄

  1. 带EXISTS关键字的子查询
EXISTS关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录。
而是返回一个真假值。True或False
当返回True时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询
#department表中存在dept_id=203,Ture
mysql> select * from employee
    ->     where exists
    ->         (select id from department where id=200);
+----+------------+--------+------+--------+
| id | name       | sex    | age  | dep_id |
+----+------------+--------+------+--------+
|  1 | egon       | male   |   18 |    200 |
|  2 | alex       | female |   48 |    201 |
|  3 | wupeiqi    | male   |   38 |    201 |
|  4 | yuanhao    | female |   28 |    202 |
|  5 | liwenzhou  | male   |   18 |    200 |
|  6 | jingliyang | female |   18 |    204 |
+----+------------+--------+------+--------+

#department表中存在dept_id=205,False
mysql> select * from employee
    ->     where exists
    ->         (select id from department where id=204);
Empty set (0.00 sec)
  1. 带EXIST
EXISTS关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录。
而是返回一个真假值。True或False
当返回True时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询
mysql> select * from emp
    -> where exists
    -> (select id from dept where id = 1);
+----+------------+--------+-----+---------+
| id | name       | sex    | age | dept_id |
+----+------------+--------+-----+---------+
|  1 | egon       | male   |  18 |       1 |
|  2 | alex       | female |  48 |       2 |
|  3 | wupeiqi    | male   |  38 |       3 |
|  4 | yuanhao    | female |  28 |       4 |
|  5 | liwenzhou  | male   |  18 |       1 |
|  6 | jingliyang | female |  18 |       3 |
+----+------------+--------+-----+---------+
6 rows in set (0.00 sec)


mysql> select * from emp
    -> where exists
    -> (select id from dept where id = 10);
Empty set (0.00 sec)
  • 练习

查询每个部门最新入职的那位员工

# 1. 准备表格
company.employee
    员工id      id                  int             
    姓名        emp_name            varchar
    性别        sex                 enum
    年龄        age                 int
    入职日期     hire_date           date
    岗位        post                varchar
    职位描述     post_comment        varchar
    薪水        salary              double
    办公室       office              int
    部门编号     depart_id           int


#创建表
create table employee(
id int not null unique auto_increment,
name varchar(20) not null,
sex enum(‘male‘,‘female‘) not null default ‘male‘, #大部分是男的
age int(3) unsigned not null default 28,
hire_date date not null,
post varchar(50),
post_comment varchar(100),
salary double(15,2),
office int, #一个部门一个屋子
depart_id int
);


#查看表结构
mysql> desc emp;
+--------------+-----------------------+------+-----+---------+----------------+
| Field        | Type                  | Null | Key | Default | Extra          |
+--------------+-----------------------+------+-----+---------+----------------+
| id           | int(11)               | NO   | PRI | NULL    | auto_increment |
| name         | varchar(20)           | NO   |     | NULL    |                |
| sex          | enum(‘male‘,‘female‘) | NO   |     | male    |                |
| age          | int(3) unsigned       | NO   |     | 28      |                |
| hire_date    | date                  | NO   |     | NULL    |                |
| post         | varchar(50)           | YES  |     | NULL    |                |
| post_comment | varchar(100)          | YES  |     | NULL    |                |
| salary       | double(15,2)          | YES  |     | NULL    |                |
| office       | int(11)               | YES  |     | NULL    |                |
| depart_id    | int(11)               | YES  |     | NULL    |                |
+--------------+-----------------------+------+-----+---------+----------------+


#插入记录
#三个部门:教学,销售,运营
insert into emp(name,sex,age,hire_date,post,salary,office,depart_id) values
(‘egon‘,‘male‘,18,‘20170301‘,‘老男孩驻沙河办事处外交大使‘,7300.33,401,1), #以下是教学部
(‘alex‘,‘male‘,78,‘20150302‘,‘teacher‘,1000000.31,401,1),
(‘wupeiqi‘,‘male‘,81,‘20130305‘,‘teacher‘,8300,401,1),
(‘yuanhao‘,‘male‘,73,‘20140701‘,‘teacher‘,3500,401,1),
(‘liwenzhou‘,‘male‘,28,‘20121101‘,‘teacher‘,2100,401,1),
(‘jingliyang‘,‘female‘,18,‘20110211‘,‘teacher‘,9000,401,1),
(‘jinxin‘,‘male‘,18,‘19000301‘,‘teacher‘,30000,401,1),
(‘成龙‘,‘male‘,48,‘20101111‘,‘teacher‘,10000,401,1),

(‘歪歪‘,‘female‘,48,‘20150311‘,‘sale‘,3000.13,402,2),#以下是销售部门
(‘丫丫‘,‘female‘,38,‘20101101‘,‘sale‘,2000.35,402,2),
(‘丁丁‘,‘female‘,18,‘20110312‘,‘sale‘,1000.37,402,2),
(‘星星‘,‘female‘,18,‘20160513‘,‘sale‘,3000.29,402,2),
(‘格格‘,‘female‘,28,‘20170127‘,‘sale‘,4000.33,402,2),

(‘张野‘,‘male‘,28,‘20160311‘,‘operation‘,10000.13,403,3), #以下是运营部门
(‘程咬金‘,‘male‘,18,‘19970312‘,‘operation‘,20000,403,3),
(‘程咬银‘,‘female‘,18,‘20130311‘,‘operation‘,19000,403,3),
(‘程咬铜‘,‘male‘,18,‘20150411‘,‘operation‘,18000,403,3),
(‘程咬铁‘,‘female‘,18,‘20140512‘,‘operation‘,17000,403,3)
;

以上是关于MySQL多表查询的主要内容,如果未能解决你的问题,请参考以下文章

Mysql多表查询

Mysql笛卡尔积详解(附实现多表查询代码实现)

Hibernate的HQL多表查询

MySQL多表查询

mysql 多表联合查询语句怎么写

mybatis-基于xml的多表查询