图片 43

多表查询

本节重点:

一、多表连接查询:       #重点:外链接语法

一、介绍

  • 多表连接查询
  • 符合条件连接查询
  • 子查询

准备表

首先先准备表

  

图片 1图片 2

员工表和部门表

 

#建表
create table department(
id int,
name varchar(20) 
);

create table employee(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') not null default 'male',
age int,
dep_id int
);

#插入数据
insert into department values
(200,'技术'),
(201,'人力资源'),
(202,'销售'),
(203,'运营');

insert into employee(name,sex,age,dep_id) values
('egon','male',18,200),
('alex','female',48,201),
('wupeiqi','male',38,201),
('yuanhao','female',28,202),
('liwenzhou','male',18,200),
('jingliyang','female',18,204)
;


#查看表结构和数据
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) | YES | | NULL | |
| sex | enum('male','female') | NO | | male | |
| age | int(11) | YES | | NULL | |
| dep_id | int(11) | YES | | NULL | |
+--------+-----------------------+------+-----+---------+----------------+

mysql> select * from department;
+------+--------------+
| id | name |
+------+--------------+
| 200 | 技术 |
| 201 | 人力资源 |
| 202 | 销售 |
| 203 | 运营 |
+------+--------------+

mysql> select * from employee;
+----+------------+--------+------+--------+
| 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 |
+----+------------+--------+------+--------+
#建表
create table department(
id int,
name varchar(20) 
);

create table employee1(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') not null default 'male',
age int,
dep_id int
);

#插入数据
insert into department values
(200,'技术'),
(201,'人力资源'),
(202,'销售'),
(203,'运营');

insert into employee1(name,sex,age,dep_id) values
('egon','male',18,200),
('alex','female',48,201),
('wupeiqi','male',38,201),
('yuanhao','female',28,202),
('liwenzhou','male',18,200),
('jingliyang','female',18,204)
;

准备工作:准备两张表,部门表(department)、员工表(employee)

View Code

查看表:

图片 3

1 .交叉连接:不适用任何匹配条件(没意义)。生成笛卡尔积

图片 4

create table department(
id int,
name varchar(20) 
);

create table employee(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') not null default 'male',
age int,
dep_id int
);

#插入数据
insert into department values
(200,'技术'),
(201,'人力资源'),
(202,'销售'),
(203,'运营');

insert into employee(name,sex,age,dep_id) values
('egon','male',18,200),
('alex','female',48,201),
('wupeiqi','male',38,201),
('yuanhao','female',28,202),
('nvshen','male',18,200),
('xiaomage','female',18,204)
;

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

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

mysql> select * from department;
+------+--------------+
| id   | name         |
+------+--------------+
|  200 | 技术         |
|  201 | 人力资源     |
|  202 | 销售         |
|  203 | 运营         |
+------+--------------+
4 rows in set (0.02 sec)

mysql> select * from employee;
+----+----------+--------+------+--------+
| 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 | nvshen   | male   |   18 |    200 |
|  6 | xiaomage | female |   18 |    204 |
+----+----------+--------+------+--------+
6 rows in set (0.00 sec)
select * from department,employee;    #笛卡尔积

图片 5

图片 6

图片 7图片 8

二、多表连接查询

ps:观察两张表,发现department表中id=203部门在employee中没有对应的员工,发现employee中id=6的员工在department表中没有对应关系。

mysql> select * from employee,department;
+----+------------+--------+------+--------+------+--------------+
| id | name       | sex    | age  | dep_id | id   | name         |
+----+------------+--------+------+--------+------+--------------+
|  1 | egon       | male   |   18 |    200 |  200 | 技术         |
|  1 | egon       | male   |   18 |    200 |  201 | 人力资源     |
|  1 | egon       | male   |   18 |    200 |  202 | 销售         |
|  1 | egon       | male   |   18 |    200 |  203 | 运营         |
|  2 | alex       | female |   48 |    201 |  200 | 技术         |
|  2 | alex       | female |   48 |    201 |  201 | 人力资源     |
|  2 | alex       | female |   48 |    201 |  202 | 销售         |
|  2 | alex       | female |   48 |    201 |  203 | 运营         |
|  3 | wupeiqi    | male   |   38 |    201 |  200 | 技术         |
|  3 | wupeiqi    | male   |   38 |    201 |  201 | 人力资源     |
|  3 | wupeiqi    | male   |   38 |    201 |  202 | 销售         |
|  3 | wupeiqi    | male   |   38 |    201 |  203 | 运营         |
|  4 | yuanhao    | female |   28 |    202 |  200 | 技术         |
|  4 | yuanhao    | female |   28 |    202 |  201 | 人力资源     |
|  4 | yuanhao    | female |   28 |    202 |  202 | 销售         |
|  4 | yuanhao    | female |   28 |    202 |  203 | 运营         |
|  5 | liwenzhou  | male   |   18 |    200 |  200 | 技术         |
|  5 | liwenzhou  | male   |   18 |    200 |  201 | 人力资源     |
|  5 | liwenzhou  | male   |   18 |    200 |  202 | 销售         |
|  5 | liwenzhou  | male   |   18 |    200 |  203 | 运营         |
|  6 | jingliyang | female |   18 |    204 |  200 | 技术         |
|  6 | jingliyang | female |   18 |    204 |  201 | 人力资源     |
|  6 | jingliyang | female |   18 |    204 |  202 | 销售         |
|  6 | jingliyang | female |   18 |    204 |  203 | 运营         |
+----+------------+--------+------+--------+------+--------------+

1.交叉连接:不适用任何匹配条件。生成笛卡尔积、

 

View Code

select * from employee1 ,department;

 

2.内链接(只连接匹配的行):按照on条件只两张表的相同的部分,连接成一张虚拟的表
select * from employee inner join department on
department.id=employee.dep_id;
select * from department inner join employee on
department.id=employee.dep_id;
select * from employee,department where
department.id=employee.dep_id;
在内连接两张表的时候不推荐使用where,推荐 inner join,因为join on
在where之前执行

2.内连接:找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了正确的结果。(只连接匹配的行)

一、多表连接查询

两张表的准备工作已完成,比如现在我要查询的员工信息以及该员工所在的部门。从该题中,我们看出既要查员工又要查该员工的部门,肯定要将两张表进行连接查询,多表连接查询。

重点:外链接语法

语法:

SELECT 字段列表
    FROM 表1 INNER|LEFT|RIGHT JOIN 表2
    ON 表1.字段 = 表2.字段;

 

(1)先看第一种情况交叉连接:不适用任何匹配条件。生成笛卡尔积(关于笛卡尔积的含义,大家百度自行补脑)。

图片 9

mysql> select * from employee,department;
+----+----------+--------+------+--------+------+--------------+
| id | name     | sex    | age  | dep_id | id   | name         |
+----+----------+--------+------+--------+------+--------------+
|  1 | egon     | male   |   18 |    200 |  200 | 技术         |
|  1 | egon     | male   |   18 |    200 |  201 | 人力资源     |
|  1 | egon     | male   |   18 |    200 |  202 | 销售         |
|  1 | egon     | male   |   18 |    200 |  203 | 运营         |
|  2 | alex     | female |   48 |    201 |  200 | 技术         |
|  2 | alex     | female |   48 |    201 |  201 | 人力资源     |
|  2 | alex     | female |   48 |    201 |  202 | 销售         |
|  2 | alex     | female |   48 |    201 |  203 | 运营         |
|  3 | wupeiqi  | male   |   38 |    201 |  200 | 技术         |
|  3 | wupeiqi  | male   |   38 |    201 |  201 | 人力资源     |
|  3 | wupeiqi  | male   |   38 |    201 |  202 | 销售         |
|  3 | wupeiqi  | male   |   38 |    201 |  203 | 运营         |
|  4 | yuanhao  | female |   28 |    202 |  200 | 技术         |
|  4 | yuanhao  | female |   28 |    202 |  201 | 人力资源     |
|  4 | yuanhao  | female |   28 |    202 |  202 | 销售         |
|  4 | yuanhao  | female |   28 |    202 |  203 | 运营         |
|  5 | nvshen   | male   |   18 |    200 |  200 | 技术         |
|  5 | nvshen   | male   |   18 |    200 |  201 | 人力资源     |
|  5 | nvshen   | male   |   18 |    200 |  202 | 销售         |
|  5 | nvshen   | male   |   18 |    200 |  203 | 运营         |
|  6 | xiaomage | female |   18 |    204 |  200 | 技术         |
|  6 | xiaomage | female |   18 |    204 |  201 | 人力资源     |
|  6 | xiaomage | female |   18 |    204 |  202 | 销售         |
|  6 | xiaomage | female |   18 |    204 |  203 | 运营         |

图片 10

 

(2)内连接:只连接匹配的行

 

图片 11

#找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了匹配的结果
#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 | nvshen  |   18 | male   | 技术         |
+----+---------+------+--------+--------------+
5 rows in set (0.00 sec)

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

图片 12

 

(3)外链接之左连接:优先显示左表全部记录

图片 13

#以左表为准,即找出所有员工信息,当然包括没有部门的员工
#本质就是:在内连接的基础上增加左边有,右边没有的结果
mysql> select employee.id,employee.name,department.name as depart_name from employee left join department on employee.dep_id=department.id;
+----+----------+--------------+
| id | name     | depart_name  |
+----+----------+--------------+
|  1 | egon     | 技术         |
|  5 | nvshen   | 技术         |
|  2 | alex     | 人力资源     |
|  3 | wupeiqi  | 人力资源     |
|  4 | yuanhao  | 销售         |
|  6 | xiaomage | NULL         |
+----+----------+--------------+
6 rows in set (0.00 sec)

图片 14

(4) 外链接之右连接:优先显示右表全部记录

图片 15

#以右表为准,即找出所有部门信息,包括没有员工的部门
#本质就是:在内连接的基础上增加右边有,左边没有的结果
mysql> select employee.id,employee.name,department.name as depart_name from employee right join department on employee.dep_id=department.id;
+------+---------+--------------+
| id   | name    | depart_name  |
+------+---------+--------------+
|    1 | egon    | 技术         |
|    2 | alex    | 人力资源     |
|    3 | wupeiqi | 人力资源     |
|    4 | yuanhao | 销售         |
|    5 | nvshen  | 技术         |
| NULL | NULL    | 运营         |
+------+---------+--------------+
6 rows in set (0.00 sec)

图片 16

 

(5) 全外连接:显示左右两个表全部记录(了解)

图片 17

#外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果
#注意:mysql不支持全外连接 full JOIN
#强调:mysql可以使用此种方式间接实现全外连接
语法:select * from employee left join department on employee.dep_id = department.id 
       union all
      select * from employee right join department on employee.dep_id = department.id;

 mysql> select * from employee left join department on employee.dep_id = department.id
          union
        select * from employee right join department on employee.dep_id = department.id
           ;
+------+----------+--------+------+--------+------+--------------+
| id   | name     | sex    | age  | dep_id | id   | name         |
+------+----------+--------+------+--------+------+--------------+
|    1 | egon     | male   |   18 |    200 |  200 | 技术         |
|    5 | nvshen   | male   |   18 |    200 |  200 | 技术         |
|    2 | alex     | female |   48 |    201 |  201 | 人力资源     |
|    3 | wupeiqi  | male   |   38 |    201 |  201 | 人力资源     |
|    4 | yuanhao  | female |   28 |    202 |  202 | 销售         |
|    6 | xiaomage | female |   18 |    204 | NULL | NULL         |
| NULL | NULL     | NULL   | NULL |   NULL |  203 | 运营         |
+------+----------+--------+------+--------+------+--------------+
7 rows in set (0.01 sec)

#注意 union与union all的区别:union会去掉相同的纪录

图片 18

 

 

图片 19图片 20

#找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了正确的结果
#department没有204这个部门,因而employee表中关于204这条员工信息没有匹配出来
select * from employee1,department where employee1.dep_id=department.id;

#上面用where表示的可以用下面的内连接表示,建议使用下面的那种方法
select * from employee1 inner join department on employee1.dep_id=department.id;

#也可以这样表示哈

select employee1.id,employee1.name,employee1.age,employee1.sex,department.name from 
employee1,department where employee1.dep_id=department.id;

二、符合条件连接查询

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

select employee.name,department.name from employee inner join department
  on employee.dep_id = department.id
  where age > 25;

 

示例2:以内连接的方式查询employee和department表,并且以age字段的升序方式显示。

select employee.id,employee.name,employee.age,department.name from employee,department
    where employee.dep_id = department.id
    and age > 25
    order by age asc;

 

mysql> select * from employee inner join department on department.id=employee.dep_id;
+----+-----------+--------+------+--------+------+--------------+
| id | name      | sex    | age  | dep_id | id   | name         |
+----+-----------+--------+------+--------+------+--------------+
|  1 | egon      | male   |   18 |    200 |  200 | 技术         |
|  2 | alex      | female |   48 |    201 |  201 | 人力资源     |
|  3 | wupeiqi   | male   |   38 |    201 |  201 | 人力资源     |
|  4 | yuanhao   | female |   28 |    202 |  202 | 销售         |
|  5 | liwenzhou | male   |   18 |    200 |  200 | 技术         |
+----+-----------+--------+------+--------+------+--------------+
5 rows in set (0.01 sec)

 图片 21

三、子查询

#1:子查询是将一个查询语句嵌套在另一个查询语句中。
#2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。
#3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字
#4:还可以包含比较运算符:= 、 !=、> 、<等

 

例子:

(1)带in关键字的子查询

图片 22

#查询平均年龄在25岁以上的部门名
select id,name from department
    where id in 
        (select dep_id from employee group by dep_id having avg(age) > 25);
# 查看技术部员工姓名
select name from employee
    where dep_id in 
        (select id from department where name='技术');
#查看不足1人的部门名
select name from department
    where id not in 
        (select dep_id from employee group by dep_id);

图片 23

 

(2)带比较运算符的子查询

图片 24

#比较运算符:=、!=、>、>=、<、<=、<>
#查询大于所有人平均年龄的员工名与年龄
mysql> select name,age from employee where age > (select avg(age) from employee);
+---------+------+
| name    | age  |
+---------+------+
| alex    |   48 |
| wupeiqi |   38 |
+---------+------+

#查询大于部门内平均年龄的员工名、年龄
思路:
      (1)先对员工表(employee)中的人员分组(group by),查询出dep_id以及平均年龄。
       (2)将查出的结果作为临时表,再对根据临时表的dep_id和employee的dep_id作为筛选条件将employee表和临时表进行内连接。
       (3)最后再将employee员工的年龄是大于平均年龄的员工名字和年龄筛选。



mysql> select t1.name,t1.age from employee as t1
             inner join
            (select dep_id,avg(age) as avg_age from employee group by dep_id) as t2
            on t1.dep_id = t2.dep_id
            where t1.age > t2.avg_age;
+------+------+
| name | age  |
+------+------+
| alex |   48 |

图片 25

 

(3)带EXISTS关键字的子查询

图片 26

#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 | nvshen   | male   |   18 |    200 |
|  6 | xiaomage | 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)

图片 27

小练习:

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

图片 28

#创建表
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 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(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 employee(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)
;

图片 29

图片 30图片 31

select * from employee as t1
inner join
(select post,max(hire_date) as new_date from employee group by post) as t2
on t1.post=t2.post
where t1.hire_date=t2.new_date;

小练习答案

 

View Code

注意:内连接的join可以忽略不写,但是还是加上看起来清楚点

3.左链接(外链接之左连接:优先显示左表全部记录):在按照on的条件取到两张表共同部分的基础上,保留左表的记录
select * from employee left join department on
department.id=employee.dep_id;

图片 32

图片 33图片 34

3.左连接:优先显示左表全部记录。

mysql> select * from employee left join department on department.id=employee.dep_id;
+----+------------+--------+------+--------+------+--------------+
| id | name       | sex    | age  | dep_id | id   | name         |
+----+------------+--------+------+--------+------+--------------+
|  1 | egon       | male   |   18 |    200 |  200 | 技术         |
|  5 | liwenzhou  | male   |   18 |    200 |  200 | 技术         |
|  2 | alex       | female |   48 |    201 |  201 | 人力资源     |
|  3 | wupeiqi    | male   |   38 |    201 |  201 | 人力资源     |
|  4 | yuanhao    | female |   28 |    202 |  202 | 销售         |
|  6 | jingliyang | female |   18 |    204 | NULL | NULL         |
+----+------------+--------+------+--------+------+--------------+
6 rows in set (0.00 sec)
#左链接:在按照on的条件取到两张表共同部分的基础上,保留左表的记录
select * from employee1 left join department on department.id=employee1.dep_id;
select * from department left join  employee1 on department.id=employee1.dep_id;

View Code

 图片 35

4.右链接(外链接之右连接:优先显示右表全部记录):在按照on的条件取到两张表共同部分的基础上,保留右表的记录
select * from employee right join department on
department.id=employee.dep_id;

图片 36

图片 37图片 38

4.右链接:优先显示右表全部记录。

mysql> select * from employee right join department on department.id=employee.dep_id;
+------+-----------+--------+------+--------+------+--------------+
| id   | name      | sex    | age  | dep_id | id   | name         |
+------+-----------+--------+------+--------+------+--------------+
|    1 | egon      | male   |   18 |    200 |  200 | 技术         |
|    2 | alex      | female |   48 |    201 |  201 | 人力资源     |
|    3 | wupeiqi   | male   |   38 |    201 |  201 | 人力资源     |
|    4 | yuanhao   | female |   28 |    202 |  202 | 销售         |
|    5 | liwenzhou | male   |   18 |    200 |  200 | 技术         |
| NULL | NULL      | NULL   | NULL |   NULL |  203 | 运营         |
+------+-----------+--------+------+--------+------+--------------+
6 rows in set (0.00 sec)
#右链接:在按照on的条件取到两张表共同部分的基础上,保留右表的记录
select * from employee1 right join department on department.id=employee1.dep_id;

select * from department right join employee1 on department.id=employee1.dep_id;

View Code

图片 39

5.full join:(注意在sql语句中没有full join)
全链接(全外连接:显示左右两个表全部记录):union
select * from employee left join department on
department.id=employee.dep_id
union
select * from employee right join department on
department.id=employee.dep_id;

图片 40

图片 41图片 42

5.全外连接:显示左右两个表的全部记录。

mysql> select * from employee left join department on department.id=employee.dep_id
    -> union
    -> select * from employee right join department on department.id=employee.dep_id;
+------+------------+--------+------+--------+------+--------------+
| id   | name       | sex    | age  | dep_id | id   | name         |
+------+------------+--------+------+--------+------+--------------+
|    1 | egon       | male   |   18 |    200 |  200 | 技术         |
|    5 | liwenzhou  | male   |   18 |    200 |  200 | 技术         |
|    2 | alex       | female |   48 |    201 |  201 | 人力资源     |
|    3 | wupeiqi    | male   |   38 |    201 |  201 | 人力资源     |
|    4 | yuanhao    | female |   28 |    202 |  202 | 销售         |
|    6 | jingliyang | female |   18 |    204 | NULL | NULL         |
| NULL | NULL       | NULL   | NULL |   NULL |  203 | 运营         |
+------+------------+--------+------+--------+------+--------------+
7 rows in set (0.00 sec)
注意:mysql不支持全外连接 full join
强调:mysql可以使用union间接实现全外连接

select * from employee1 left join department on department.id=employee1.dep_id
union
select * from employee1 right join department on department.id=employee1.dep_id; 

View Code

图片 43

#注意 union与union all的区别:union会去掉相同的纪录

三、符合条件连接查询

6.子查询:
  1:子查询是将一个查询语句嵌套在另一个查询语句中。
  2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。
  3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT
EXISTS等关键字
  4:还可以包含比较运算符:= 、 !=、> 、<等

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

select * from employee1 inner join department on employee1.dep_id=department.id 

and age>25;
1 带IN关键字的子查询:
#查询employee表,但dep_id必须在department表中出现过
select * from employee
    where dep_id in
        (select id from department);

 

图片 44图片 45

示例2:以内连接的方式查询employee和department表,并且以age字段的升序方式显示

select * from employee1 inner join department on employee1.dep_id=department.id 
=

and age>25 and age>25 order by age asc;
mysql> select * from employee where dep_id in (select id from department where name in ('技术','销售'));
+----+-----------+--------+------+--------+
| id | name      | sex    | age  | dep_id |
+----+-----------+--------+------+--------+
|  1 | egon      | male   |   18 |    200 |
|  4 | yuanhao   | female |   28 |    202 |
|  5 | liwenzhou | male   |   18 |    200 |
+----+-----------+--------+------+--------+
3 rows in set (0.02 sec)

四、子查询

View Code

#1:子查询是将一个查询语句嵌套在另一个查询语句中。
#2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。
#3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字
#4:还可以包含比较运算符:= 、 !=、> 、<等
2 带比较运算符的子查询:
#比较运算符:=、!=、>、>=、<、<=、<>

小练习

图片 46图片 47

#查询平均年龄在25岁以上的部门名
select name from department where id in (
select dep_id from employee group by dep_id having avg(age) > 25
);
#查看技术部员工姓名
select name from employee where dep_id = (select id from department where name='技术');

#查看小于2人的部门名
select name from department where id in (
select dep_id from employee1 group by dep_id having count(id) < 2
)
union
select name from department where id not in (select distinct dep_id from employee1);

#提取空部门                              #有人的部门
select * from department where id not in (select distinct dep_id from employee1);


或者:
select name from department where id in
(
select dep_id from employee1 group by dep_id having count(id) < 2
union
select id from department where id not in (select distinct dep_id from employee1);
);
#查询平均年龄在25岁以上的部门名
select name from department where id in (
select dep_id from employee group by dep_id having avg(age) > 25
);

+--------------+
| name         |
+--------------+
| 人力资源     |
| 销售         |
+--------------+
2 rows in set (0.00 sec)

#查看技术部员工姓名
select name from employee where dep_id = (select id from department where name='技术');

+-----------+
| name      |
+-----------+
| egon      |
| liwenzhou |
+-----------+
2 rows in set (0.00 sec)

#查看小于2人的部门名
select name from department where id in (
select dep_id from employee group by dep_id having count(id) < 2
)
union
select name from department where id not in (select distinct dep_id from employee);

+--------+
| name   |
+--------+
| 销售   |
| 运营   |
+--------+
2 rows in set (0.01 sec)


#提取空部门                              #没有人的部门
select * from department where id not in (select distinct dep_id from employee);

+------+--------+
| id   | name   |
+------+--------+
|  203 | 运营   |
+------+--------+
1 row in set (0.00 sec)

或者:
select name from department where id in
(
select dep_id from employee group by dep_id having count(id) < 2
union
select id from department where id not in (select distinct dep_id from employee)
);

+--------+
| name   |
+--------+
| 销售   |
| 运营   |
+--------+
2 rows in set (0.00 sec)

五、综合练习

View Code

一、SELECT语句关键字的定义顺序

3 带EXISTS关键字的子查询:
exists关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录。
而是返回一个真假值。True或False
当返回True时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询

图片 48图片 49

图片 50图片 51

1 SELECT DISTINCT <select_list>
2 FROM <left_table>
3 <join_type> JOIN <right_table>
4 ON <join_condition>
5 WHERE <where_condition>
6 GROUP BY <group_by_list>
7 HAVING <having_condition>
8 ORDER BY <order_by_condition>
9 LIMIT <limit_number>
mysql> select * from employee where exists (select id from department where name='hahahahah');
Empty set (0.00 sec)

mysql> select * from employee where exists (select id from department where name='技术');
+----+------------+--------+------+--------+
| 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 |
+----+------------+--------+------+--------+
6 rows in set (0.00 sec)

SELECT语句关键字的定义顺序

View Code

二 、SELECT语句关键字的执行顺序

(7)     SELECT 
(8)     DISTINCT <select_list>
(1)     FROM <left_table>
(3)     <join_type> JOIN <right_table>
(2)     ON <join_condition>
(4)     WHERE <where_condition>
(5)     GROUP BY <group_by_list>
(6)     HAVING <having_condition>
(9)     ORDER BY <order_by_condition>
(10)    LIMIT <limit_number>

init.sql文件内容

图片 52View Code

 从init.sql文件中导入数据

#准备表、记录
mysql> create database db1;
mysql> use db1;
mysql> source /root/init.sql

图片 53图片 54

 1 1、查询所有的课程的名称以及对应的任课老师姓名
 2 
 3 2、查询学生表中男女生各有多少人
 4 
 5 3、查询物理成绩等于100的学生的姓名
 6 
 7 4、查询平均成绩大于八十分的同学的姓名和平均成绩
 8 
 9 5、查询所有学生的学号,姓名,选课数,总成绩
10 
11 6、 查询姓李老师的个数
12 
13 7、 查询没有报李平老师课的学生姓名
14 
15 8、 查询物理课程比生物课程高的学生的学号
16 
17 9、 查询没有同时选修物理课程和体育课程的学生姓名
18 
19 10、查询挂科超过两门(包括两门)的学生姓名和班级
20 、查询选修了所有课程的学生姓名
21 
22 12、查询李平老师教的课程的所有成绩记录
23  
24 13、查询全部学生都选修了的课程号和课程名
25 
26 14、查询每门课程被选修的次数
27 
28 15、查询之选修了一门课程的学生姓名和学号
29 
30 16、查询所有学生考出的成绩并按从高到低排序(成绩去重)
31 
32 17、查询平均成绩大于85的学生姓名和平均成绩
33 
34 18、查询生物成绩不及格的学生姓名和对应生物分数
35 
36 19、查询在所有选修了李平老师课程的学生中,这些课程(李平老师的课程,不是所有课程)平均成绩最高的学生姓名
37 
38 20、查询每门课程成绩最好的前两名学生姓名
39 
40 21、查询不同课程但成绩相同的学号,课程号,成绩
41 
42 22、查询没学过“叶平”老师课程的学生姓名以及选修的课程名称;
43 
44 23、查询所有选修了学号为1的同学选修过的一门或者多门课程的同学学号和姓名;
45 
46 24、任课最多的老师中学生单科成绩最高的学生姓名

题目

答案待续。。。。

图片 55图片 56

  1 1、查询所有的课程的名称以及对应的任课老师姓名
  2 select cname 课程名称,tname 老师姓名 from course  left join teacher on course.teacher_id = teacher.tid;
  3 
  4 2、查询学生表中男女生各有多少人
  5 select gender ,count(gender) from student group by gender;
  6 
  7 3、查询物理成绩等于100的学生的姓名
  8 select sname from student inner join score on student.sid = score.student_id
  9 join course on score.course_id = course.cid
 10 where cname = '物理' and num = 100;
 11 
 12 4、查询平均成绩大于八十分的同学的姓名和平均成绩
 13 (1):
 14 select sname 姓名,avg(num) 平均成绩 from student inner join score on student.sid = score.student_id 
 15 group by student_id having avg(num)>80;
 16 (2):
 17 select sname,avg(num) from student inner join score on student.sid = score.student_id 
 18 group by student_id having avg(num)>80
 19 
 20 5、查询所有学生的学号,姓名,选课数,总成绩
 21 select student.sid 学号,sname 姓名,count(course_id) 选课数,sum(num) 总成绩 from student left join score on student.sid = score.student_id
 22 group by student.sid ;
 23 6、 查询姓李老师的个数
 24 select count(tid) from teacher where tname like '李%';
 25 
 26 7、 查询没有报李平老师课的学生姓名
 27 select sname 姓名 from student where sid not in (
 28 select student_id from score where course_id in(
 29 select cid from course where teacher_id =(
 30 select tid from teacher where tname = '李平老师'
 31 )));
 32 
 33 8、 查询物理课程比生物课程高的学生的学号
 34 select t1.student_id  学号 from 
 35 (select student_id ,num from score inner join course on score.course_id=course.cid  where cname='物理' )as t1
 36 inner join 
 37 (select student_id , num from score inner join course on score.course_id=course.cid  where cname = '生物') as t2
 38 on t1.student_id = t2.student_id
 39 where t1.num>t2.num;
 40 
 41 
 42 
 43 9、 查询没有同时选修物理课程和体育课程的学生姓名
 44 (1):
 45 select sname from student inner join score on student.sid = score.student_id
 46 join course on course.cid=score.course_id and cname in ('物理','体育') 
 47 group by student_id having count(course_id)!=2;
 48 
 49 (2):
 50 select sname from student join score  on student.sid = score.student_id
 51 join course on course.cid=score.course_id where cname ='物理' or cname= '体育'
 52 group by student_id having count(course_id) !=2;
 53 
 54 10、查询挂科超过两门(包括两门)的学生姓名和班级
 55 select sname 姓名,caption 班级 from student inner join score on student.sid = score.course_id
 56 join class on class.cid = score.course_id
 57 where num<60 group by student_id having count(course_id)>=2;
 58 
 59 11、查询选修了所有课程的学生姓名
 60 (1)
 61 select sname 姓名 ,所有的课程数 from student inner join 
 62 (select student_id,count(course_id) 所有的课程数 from score group by student_id having count(course_id) = (
 63 select count(cid) from course)) as t1
 64 on t1.student_id = student.sid;
 65 
 66 (2)
 67 select sname,count(course_id) from student inner join score on student.sid = score.student_id
 68 group by student_id having count(course_id)=(select count(cid) from course);
 69 
 70 12、查询李平老师教的课程的所有成绩记录
 71 (1):
 72 select num from score inner join course on course.cid=score.course_id
 73 join teacher on teacher.tid=course.teacher_id
 74 where tname = '李平老师';
 75 
 76 (2):
 77 select num from score where course_id in(select cid from course where teacher_id=
 78 (select tid from teacher where tname='李平老师'));
 79 
 80 13、查询全部学生都选修了的课程号和课程名
 81 select cid 课程号,cname 课程名 from course
 82 select ;
 83 14、查询每门课程被选修的次数 
 84 (1)
 85 select course.cname,count(student_id) 选课人数 from score inner join course on score.course_id=course.cid
 86 group by course_id;
 87 
 88 (2):也可以按照name分组
 89 select course.cname,count(student_id) 选课人数 from score inner join course on score.course_id=course.cid
 90 group by cname;
 91 
 92 15、查询之选修了一门课程的学生姓名和学号
 93 select sname 姓名,student_id 学号 from student inner join score on student.sid = score.student_id
 94 group by student_id having count(course_id)=1;
 95 
 96 16、查询所有学生考出的成绩并按从高到低排序(成绩去重)
 97 select distinct num from score order by num desc;
 98 
 99 17、查询平均成绩大于85的学生姓名和平均成绩
100 (1):
101 select sname 姓名,avg(num) 平均成绩 from student inner join score on student.sid = score.student_id
102 group by student_id having avg(num)>85;
103 
104 (2):
105 select student.sname,avg_num from student inner join
106 (select student_id,avg(num) as avg_num from score group by student_id having avg(num) > 85
107 ) t1
108 on student.sid=t1.student_id;
109 
110 
111 18、查询生物成绩不及格的学生姓名和对应生物分数
112 (1):
113 select student.sname ,num 生物成绩 from student inner join score on student.sid = score.student_id
114 join course on course.cid=score.course_id
115 where cname='生物' and num<60;
116 
117 (2):
118 select student.sname,t1.num from student inner join
119 (
120 select student_id,num from score
121 where course_id=(select cid from course where cname='生物') and num < 60
122 ) t1
123 on t1.student_id=student.sid
124 ;
125 
126 19、查询在所有选修了李平老师课程的学生中,这些课程(李平老师的课程,不是所有课程)平均成绩最高的学生姓名
127 select sname from student where sid=(
128 select student_id from score where course_id in (
129 select cid from course where teacher_id=(select tid from teacher where tname='李平老师')
130 ) group by student_id order by avg(num) desc limit 1
131 )

答案

 

7.!!!重中之重:务必搞清楚sql逻辑查询语句的执行顺序

SELECT语句关键字的定义顺序

SELECT DISTINCT <select_list>
FROM <left_table>
<join_type> JOIN <right_table>
ON <join_condition>
WHERE <where_condition>
GROUP BY <group_by_list>
HAVING <having_condition>
ORDER BY <order_by_condition>
LIMIT <limit_number>

SELECT语句关键字的执行顺序

(7)     SELECT 
(8)     DISTINCT <select_list>
(1)     FROM <left_table>
(3)     <join_type> JOIN <right_table>
(2)     ON <join_condition>
(4)     WHERE <where_condition>
(5)     GROUP BY <group_by_list>
(6)     HAVING <having_condition>
(9)     ORDER BY <order_by_condition>
(10)    LIMIT <limit_number>

 

图片 57图片 58

三 准备表和数据
1. 新建一个测试数据库TestDB;
create database TestDB;
2.创建测试表table1和table2;

CREATE TABLE table1
 (
     customer_id VARCHAR(10) NOT NULL,
     city VARCHAR(10) NOT NULL,
     PRIMARY KEY(customer_id)
 )ENGINE=INNODB DEFAULT CHARSET=UTF8;

 CREATE TABLE table2
 (
     order_id INT NOT NULL auto_increment,
     customer_id VARCHAR(10),
     PRIMARY KEY(order_id)
 )ENGINE=INNODB DEFAULT CHARSET=UTF8;

3.插入测试数据;

 INSERT INTO table1(customer_id,city) VALUES('163','hangzhou');
 INSERT INTO table1(customer_id,city) VALUES('9you','shanghai');
 INSERT INTO table1(customer_id,city) VALUES('tx','hangzhou');
 INSERT INTO table1(customer_id,city) VALUES('baidu','hangzhou');

 INSERT INTO table2(customer_id) VALUES('163');
 INSERT INTO table2(customer_id) VALUES('163');
 INSERT INTO table2(customer_id) VALUES('9you');
 INSERT INTO table2(customer_id) VALUES('9you');
 INSERT INTO table2(customer_id) VALUES('9you');
 INSERT INTO table2(customer_id) VALUES('tx');
 INSERT INTO table2(customer_id) VALUES(NULL);

准备工作做完以后,table1和table2看起来应该像下面这样:

mysql> select * from table1;
 +-------------+----------+
 | customer_id | city     |
 +-------------+----------+
 | 163         | hangzhou |
 | 9you        | shanghai |
 | baidu       | hangzhou |
 | tx          | hangzhou |
 +-------------+----------+
 4 rows in set (0.00 sec)

 mysql> select * from table2;
 +----------+-------------+
 | order_id | customer_id |
 +----------+-------------+
 |        1 | 163         |
 |        2 | 163         |
 |        3 | 9you        |
 |        4 | 9you        |
 |        5 | 9you        |
 |        6 | tx          |
 |        7 | NULL        |
 +----------+-------------+
 7 rows in set (0.00 sec)


四 准备SQL逻辑查询测试语句

#查询来自杭州,并且订单数少于2的客户。
 SELECT a.customer_id, COUNT(b.order_id) as total_orders
 FROM table1 AS a
 LEFT JOIN table2 AS b
 ON a.customer_id = b.customer_id
 WHERE a.city = 'hangzhou'
 GROUP BY a.customer_id
 HAVING count(b.order_id) < 2
 ORDER BY total_orders DESC;


五 执行顺序分析
在这些SQL语句的执行过程中,都会产生一个虚拟表,用来保存SQL语句的执行结果(这是重点),我现在就来跟踪这个虚拟表的变化,得到最终的查询结果的过程,来分析整个SQL逻辑查询的执行顺序和过程。
执行FROM语句
第一步,执行FROM语句。我们首先需要知道最开始从哪个表开始的,这就是FROM告诉我们的。现在有了<left_table>和<right_table>两个表,我们到底从哪个表开始,还是从两个表进行某种联系以后再开始呢?它们之间如何产生联系呢?——笛卡尔积
关于什么是笛卡尔积,请自行Google补脑。经过FROM语句对两个表执行笛卡尔积,会得到一个虚拟表,暂且叫VT1(vitual table 1),内容如下:

+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| 163         | hangzhou |        1 | 163         |
| 9you        | shanghai |        1 | 163         |
| baidu       | hangzhou |        1 | 163         |
| tx          | hangzhou |        1 | 163         |
| 163         | hangzhou |        2 | 163         |
| 9you        | shanghai |        2 | 163         |
| baidu       | hangzhou |        2 | 163         |
| tx          | hangzhou |        2 | 163         |
| 163         | hangzhou |        3 | 9you        |
| 9you        | shanghai |        3 | 9you        |
| baidu       | hangzhou |        3 | 9you        |
| tx          | hangzhou |        3 | 9you        |
| 163         | hangzhou |        4 | 9you        |
| 9you        | shanghai |        4 | 9you        |
| baidu       | hangzhou |        4 | 9you        |
| tx          | hangzhou |        4 | 9you        |
| 163         | hangzhou |        5 | 9you        |
| 9you        | shanghai |        5 | 9you        |
| baidu       | hangzhou |        5 | 9you        |
| tx          | hangzhou |        5 | 9you        |
| 163         | hangzhou |        6 | tx          |
| 9you        | shanghai |        6 | tx          |
| baidu       | hangzhou |        6 | tx          |
| tx          | hangzhou |        6 | tx          |
| 163         | hangzhou |        7 | NULL        |
| 9you        | shanghai |        7 | NULL        |
| baidu       | hangzhou |        7 | NULL        |
| tx          | hangzhou |        7 | NULL        |
+-------------+----------+----------+-------------+

总共有28(table1的记录条数 * table2的记录条数)条记录。这就是VT1的结果,接下来的操作就在VT1的基础上进行。
执行ON过滤
执行完笛卡尔积以后,接着就进行ON a.customer_id = b.customer_id条件过滤,根据ON中指定的条件,去掉那些不符合条件的数据,得到VT2表,内容如下:

+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| 163         | hangzhou |        1 | 163         |
| 163         | hangzhou |        2 | 163         |
| 9you        | shanghai |        3 | 9you        |
| 9you        | shanghai |        4 | 9you        |
| 9you        | shanghai |        5 | 9you        |
| tx          | hangzhou |        6 | tx          |
+-------------+----------+----------+-------------+

VT2就是经过ON条件筛选以后得到的有用数据,而接下来的操作将在VT2的基础上继续进行。
添加外部行
这一步只有在连接类型为OUTER JOIN时才发生,如LEFT OUTER JOIN、RIGHT OUTER JOIN和FULL OUTER JOIN。在大多数的时候,我们都是会省略掉OUTER关键字的,但OUTER表示的就是外部行的概念。
LEFT OUTER JOIN把左表记为保留表,得到的结果为:

+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| 163         | hangzhou |        1 | 163         |
| 163         | hangzhou |        2 | 163         |
| 9you        | shanghai |        3 | 9you        |
| 9you        | shanghai |        4 | 9you        |
| 9you        | shanghai |        5 | 9you        |
| tx          | hangzhou |        6 | tx          |
| baidu       | hangzhou |     NULL | NULL        |
+-------------+----------+----------+-------------+

RIGHT OUTER JOIN把右表记为保留表,得到的结果为:

+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| 163         | hangzhou |        1 | 163         |
| 163         | hangzhou |        2 | 163         |
| 9you        | shanghai |        3 | 9you        |
| 9you        | shanghai |        4 | 9you        |
| 9you        | shanghai |        5 | 9you        |
| tx          | hangzhou |        6 | tx          |
| NULL        | NULL     |        7 | NULL        |
+-------------+----------+----------+-------------+

FULL OUTER JOIN把左右表都作为保留表,得到的结果为:

+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| 163         | hangzhou |        1 | 163         |
| 163         | hangzhou |        2 | 163         |
| 9you        | shanghai |        3 | 9you        |
| 9you        | shanghai |        4 | 9you        |
| 9you        | shanghai |        5 | 9you        |
| tx          | hangzhou |        6 | tx          |
| baidu       | hangzhou |     NULL | NULL        |
| NULL        | NULL     |        7 | NULL        |
+-------------+----------+----------+-------------+

添加外部行的工作就是在VT2表的基础上添加保留表中被过滤条件过滤掉的数据,非保留表中的数据被赋予NULL值,最后生成虚拟表VT3。
由于我在准备的测试SQL查询逻辑语句中使用的是LEFT JOIN,过滤掉了以下这条数据:
| baidu       | hangzhou |     NULL | NULL        |
现在就把这条数据添加到VT2表中,得到的VT3表如下:

+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| 163         | hangzhou |        1 | 163         |
| 163         | hangzhou |        2 | 163         |
| 9you        | shanghai |        3 | 9you        |
| 9you        | shanghai |        4 | 9you        |
| 9you        | shanghai |        5 | 9you        |
| tx          | hangzhou |        6 | tx          |
| baidu       | hangzhou |     NULL | NULL        |
+-------------+----------+----------+-------------+

接下来的操作都会在该VT3表上进行。
执行WHERE过滤
对添加外部行得到的VT3进行WHERE过滤,只有符合<where_condition>的记录才会输出到虚拟表VT4中。当我们执行WHERE a.city = 'hangzhou'的时候,就会得到以下内容,并存在虚拟表VT4中:

+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| 163         | hangzhou |        1 | 163         |
| 163         | hangzhou |        2 | 163         |
| tx          | hangzhou |        6 | tx          |
| baidu       | hangzhou |     NULL | NULL        |
+-------------+----------+----------+-------------+

但是在使用WHERE子句时,需要注意以下两点:
由于数据还没有分组,因此现在还不能在WHERE过滤器中使用where_condition=MIN(col)这类对分组统计的过滤;
由于还没有进行列的选取操作,因此在SELECT中使用列的别名也是不被允许的,如:SELECT city as c FROM t WHERE c='shanghai';是不允许出现的。
执行GROUP BY分组
GROU BY子句主要是对使用WHERE子句得到的虚拟表进行分组操作。我们执行测试语句中的GROUP BY a.customer_id,就会得到以下内容(默认只显示组内第一条):

+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| 163         | hangzhou |        1 | 163         |
| baidu       | hangzhou |     NULL | NULL        |
| tx          | hangzhou |        6 | tx          |
+-------------+----------+----------+-------------+

得到的内容会存入虚拟表VT5中,此时,我们就得到了一个VT5虚拟表,接下来的操作都会在该表上完成。
执行HAVING过滤
HAVING子句主要和GROUP BY子句配合使用,对分组得到的VT5虚拟表进行条件过滤。当我执行测试语句中的HAVING count(b.order_id) < 2时,将得到以下内容:
+-------------+----------+----------+-------------+
| customer_id | city     | order_id | customer_id |
+-------------+----------+----------+-------------+
| baidu       | hangzhou |     NULL | NULL        |
| tx          | hangzhou |        6 | tx          |
+-------------+----------+----------+-------------+
这就是虚拟表VT6。
SELECT列表
现在才会执行到SELECT子句,不要以为SELECT子句被写在第一行,就是第一个被执行的。
我们执行测试语句中的SELECT a.customer_id, COUNT(b.order_id) as total_orders,从虚拟表VT6中选择出我们需要的内容。我们将得到以下内容:
+-------------+--------------+
| customer_id | total_orders |
+-------------+--------------+
| baidu       |            0 |
| tx          |            1 |
+-------------+--------------+
还没有完,这只是虚拟表VT7。
执行DISTINCT子句
如果在查询中指定了DISTINCT子句,则会创建一张内存临时表(如果内存放不下,就需要存放在硬盘了)。这张临时表的表结构和上一步产生的虚拟表VT7是一样的,不同的是对进行DISTINCT操作的列增加了一个唯一索引,以此来除重复数据。
由于我的测试SQL语句中并没有使用DISTINCT,所以,在该查询中,这一步不会生成一个虚拟表。
执行ORDER BY子句
对虚拟表中的内容按照指定的列进行排序,然后返回一个新的虚拟表,我们执行测试SQL语句中的ORDER BY total_orders DESC,就会得到以下内容:
+-------------+--------------+
| customer_id | total_orders |
+-------------+--------------+
| tx          |            1 |
| baidu       |            0 |
+-------------+--------------+
可以看到这是对total_orders列进行降序排列的。上述结果会存储在VT8中。
执行LIMIT子句
LIMIT子句从上一步得到的VT8虚拟表中选出从指定位置开始的指定行数据。对于没有应用ORDER BY的LIMIT子句,得到的结果同样是无序的,所以,很多时候,我们都会看到LIMIT子句会和ORDER BY子句一起使用。
MySQL数据库的LIMIT支持如下形式的选择:
LIMIT n, m
表示从第n条记录开始选择m条记录。而很多开发人员喜欢使用该语句来解决分页问题。对于小数据,使用LIMIT子句没有任何问题,当数据量非常大的时候,使用LIMIT n, m是非常低效的。因为LIMIT的机制是每次都是从头开始扫描,如果需要从第60万行开始,读取3条数据,就需要先扫描定位到60万行,然后再进行读取,而扫描的过程是一个非常低效的过程。所以,对于大数据处理时,是非常有必要在应用层建立一定的缓存机制(现在的大数据处理,大都使用缓存)

View Code