Fork me on GitHub

mysql-数据库增删改查

增删改查

mysql数据操作:DML

在mysql管理软件中,可以通过sql语句的DML语言来实现数据的操作:

  1. INSERT插入数据
  2. UPDATE更新数据
  3. DELETE删除数据
  4. SELECT查询数据

插入数据 insert

语法

1. 插入完整数据(顺序插入)
语法一:
INSERT INTO 表名(字段一,字段二,字段n) VALUES(值1,值2,值n);

语法二:
INSERT INTO 表名 VALUES(值1,值2,值n);

2. 指定字段插入数据
语法:
INSERT INTO 表名(字段2,字段3,字段n) VALUES(值1,值2,值3);

3. 插入多条记录
语法:
INSERT INTO 表民 VALUES
        (值1,值2,值3),
        (值1,值2,值3),
        (值1,值2,值3);

4. 插入查询结果
语法:
INSERT INTO 表民(字段1,字段2,字段3) SELECT 字段1,字段2,字段3 FROM 表2;

更新数据 update

语法

语法:
    UPDATE 表名 SET 
        字段1=值1,
        字段2=值2,
        WHERE 条件;

示例:
    密码加密时password需要加密 所以需要使用password=password('明文密码')
    正常加载数据时 只需要=新的值即可
    UPDATE mysql.user SET password=password('123') WHERE user='root' and host='localhost';

删除数据 DELETE

语法

语法:
    # 删除所有符合条件的行
    DELETE FROM 表名 WHERE 条件;

示例:
    DELETE FROM mysql.user WHERE password='';
    delete from mysql.user where user='mhy' and host='localhost';

查询数据 SELECT

单表查询

单表查询语法

SELETE DISTINCT 字段1,字段2... FROM 表民
WHERE 条件
GROUP BY 字段
HAVING 筛选
ORDER BY 字段排序
LIMIT 限制条数

关键字执行的优先级

FROM  # 1.找到表:from
WHERE # 2.拿着where指定的约束条件,去文件/表中取出一条条记录
GROUP BY # 3.将取出的一条条记录进行分组group by,如果没有group by,则整体作为一组
SELECT # 4.执行select(去重)
DISTINCT  # 4.执行select(去重)
HAVING  # 5.将分组的结果进行having过滤
ORDER BY # 6.将结果按条件排序:order by
LIMIT # 7.限制结果的显示条数

数据准备

# 创建表
    create table employee(
    id int not null unique auto_increment,
    emp_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 |
    | emp_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    |                |
    +--------------+-----------------------+------+-----+---------+----------------+
    10 rows in set (0.43 sec)

# 插入数据
#三个部门:教学,销售,运营
    insert into employee(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)

# ps:如果在windows系统中,插入中文字符,select的结果为空白,可以将所有字符编码统一设置成gbk

简单查询

# 查看数据
    SELECT id,emp_name,sex,age,hire_date,post,post_comment,salary,office,depart_id FROM employee;
    
    SELECT * FROM employee;
    
    select id,emp_name from employee;

# 避免重复查询
    select distinct post from employee;

# 通过四则运算查询
    select emp_name,salary*12 from employee;
    select emp_name,salary*12 as Annual_salary from employee;
    select emp_name,salary*12 Annual_salary from employee;

# 定义显示格式
    concat() # 函数 用于连接字符串,相当于python的字符串格式化
    select concat('姓名: ',emp_name,' 年薪:',salary*12) as Anuual_salary from employee;

    contat_ws() # 第一个参数为分隔符
    select concat_ws(' : ',emp_name,salary*12) as Anuual_salary from employee;

    结合case语句
        SELECT
            (
        CASE
            
            WHEN emp_name = 'jingliyang' THEN
            emp_name 
            WHEN emp_name = 'alex' THEN
            concat( emp_name, '_BIGSB' ) ELSE concat( emp_name, 'SB' ) 
        END 
            ) AS new_name 
        FROM
        employee;

练习

  1. 查出所有员工的名字,薪资,格式为:
    <名字:egon> <薪资:3000>
  2. 查出所有的岗位(去掉重复)
  3. 查出所有员工名字,以及他们的年薪,年薪的字段名为annual_year
答案
 
 select concat('<名字:',emp_name,'>','<薪资:',salary,'>') from employee;
 select distinct post from employee;
 select emp_name,salary*12 as annual_year from employee;
  

where约束

where语句中可以使用

  1. 比较运算符:> < >= <= = <> != (这两的意思都是不等于)
  2. between 80 and 100 值在80和100之间
  3. in (80,90,100) 值是80或者90或者100
  4. like 'e%';通配符可以是%或者_
    • % 表示任意多字符
    • _ 表示任意一个字符
  5. 逻辑运算符:在多个条件中可以使用逻辑运算符 and or not
# 单条件查询
SELECT emp_name from employee where post = 'sale';

# 多条件查询
select emp_name from employee where post = 'sale' and salary > 3000;

# 关键字 between and 
select emp_name from employee where salary BETWEEN 10000 AND 100000;

select emp_name from employee where salary not between 5000 and 2000000;

# 关键字is null (判断某个字段是否为null,需要用is)
select emp_name from employee where post_comment is null;

select emp_name from employee where post_comment is not null;

SELECT emp_name,post_comment FROM employee 
        WHERE post_comment=''; 注意''是空字符串,不是null
    ps:
        执行
        update employee set post_comment='' where id=2;
        再用上条查看,就会有结果了

# 关键字 in 集合查询

select emp_name,salary from employee where salary=9000 or salary=8300;

select emp_name,salary from employee where salary in (9000,8300,4000.33);

select emp_name,salary from employee where salary not in (9000,8300,4000.33);

# 关键字LIKE模糊查询
    通配符'%'
    SELECT * FROM employee WHERE emp_name LIKE 'eg%';

    通配符'_'
    SELECT * FROM employee WHERE emp_name LIKE 'al__';
练习
  1. 查看岗位是teacher的员工姓名、年龄
  2. 查看岗位是teacher且年龄大于30岁的员工姓名、年龄
  3. 查看岗位是teacher且薪资在9000-10000范围内的员工姓名、年龄、薪资
  4. 查看岗位描述不为NULL的员工信息
  5. 查看岗位是teacher且薪资是10000或9000或30000的员工姓名、年龄、薪资
  6. 查看岗位是teacher且薪资不是10000或9000或30000的员工姓名、年龄、薪资
  7. 查看岗位是teacher且名字是jin开头的员工姓名、年薪
答案
 
select emp_name,age from employee where post = 'teacher';
select emp_name,age from employee where post='teacher' and age > 30; 
select emp_name,age,salary from employee where post='teacher' and salary between 9000 and 10000;
select * from employee where post_comment is not null;
select emp_name,age,salary from employee where post='teacher' and salary in (10000,9000,30000);
select emp_name,age,salary from employee where post='teacher' and salary not in (10000,9000,30000);
select emp_name,salary*12 from employee where post='teacher' and emp_name like 'jin%';
  

group by 分组

单独使用group by关键字 分组

select post from employee group by post;
# 注意:我们按照post字段分组,那么select 查询的字段只能是post,想要获取组内的其他相关信息,需要用到函数

# group by 和 group_concat()函数一起使用:
    # 按照岗位分组,并查看组内成员名
    select post,group_concat(emp_name) from employee group by post;
    select post,group_concat(emp_name) as name from employee group by post;

# group by 和聚合函数一起使用:
    # 按照岗位分组,并查看每个组有多少人
    select post,count(id) as count from employee group by post;

强调:

如果我们用unique的字段作为分组的依据,则每一条记录自成一组,这种分组没有意义
多条记录之间的某个字段值相同,该字段通常用来作为分组的依据

聚合函数

强调:聚合函数聚合的是组的数据,若是没有组,则默认一个组

# 计数函数 统计数据的条数
select count(*) from employee;
select count(*) from employee where depart_id = 1;

# 平均值函数 计算符合条件的值的平均值
select avg(salary) from employee;

# 相加函数 计算结果的和
select sum(salary) from employee;
select sum(salary) from employee where depart_id = 3;

# 最大值函数 返回值中最大的值
select max(salary) from employee;

# 最小值函数 返回值中最小的值
select min(salary) from employee;
练习
  1. 查询岗位名以及岗位包含的所有员工名字
  2. 查询岗位名以及各岗位内包含的员工个数
  3. 查询公司内男员工和女员工的个数
  4. 查询岗位名以及各岗位的平均薪资
  5. 查询岗位名以及各岗位的最高薪资
  6. 查询岗位名以及各岗位的最低薪资
  7. 查询男员工与男员工的平均薪资,女员工与女员工的平均薪资
答案
 
1. select post,group_concat(emp_name) as name from employee group by post;
2. select post,count(id) as name from employee group by post;
3. select sex,count(id) as sex_count from employee group by sex;
4. select post,avg(salary) as avg_salary from employee group by post;
5. select post,max(salary) as avg_salary from employee group by post;
6. select post,min(salary) as avg_salary from employee group by post;
7. select sex,avg(salary) as sex_salary from employee group by sex; 
  

HAVING过滤

注: HAVING与WHERE不一样的地方在于!!!

! ! ! 优先级从高到底: where > group by > having

  1. where 发生在group by 分组之前, 因而where中可以有任何字段,但是绝对不能再使用聚合函数
  2. having 发生在group by 分组之后,因而having中可以使用分组的字段, 无法直接取到其他字段,可以使用聚合函数
测试
mysql> select @@sql_mode;  # 查看全局的一些约束
+------------------------+
| @@sql_mode             |
+------------------------+
| NO_ENGINE_SUBSTITUTION |
+------------------------+
1 row in set (0.00 sec)

mysql> select * from employee where salary > 100000;
+----+-----------+--------+-----+------------+-----------------+--------------------------+------------+--------+-----------+
| id | emp_name  | sex    | age | hire_date  | post            | post_comment             | salary     | office | depart_id |
+----+-----------+--------+-----+------------+-----------------+--------------------------+------------+--------+-----------+
|  2 | alex      | male   |  78 | 2015-03-02 | teacher         | NULL                     | 1000000.31 |    401 |         1 |
| 19 | 麻花有    | female |  25 | 2019-09-22 | 中国外交部      | 中国未来全靠你们         |  999999.99 |    404 |         4 |
+----+-----------+--------+-----+------------+-----------------+--------------------------+------------+--------+-----------+
2 rows in set (0.00 sec)

# 错误,分组后无法直接取到salary字段
mysql> select post,group_concat(emp_name) from employee group by post HAVING salary > 100000;
ERROR 1054 (42S22): Unknown column 'salary' in 'having clause'


mysql> select post,group_concat(emp_name) from employee group by post having avg(salary) > 100000;
+-----------------+--------------------------------------------------+
| post            | group_concat(emp_name)                           |
+-----------------+--------------------------------------------------+
| teacher         | jinxin,jingliyang,liwenzhou,yuanhao,wupeiqi,alex |
| 中国外交部        | 麻花有                                            |
+-----------------+--------------------------------------------------+
2 rows in set (0.00 sec)
练习
  1. 查询各岗位内包含的员工个数小于2的岗位名、岗位内包含员工名字、个数
  2. 查询各岗位平均薪资大于10000的岗位名、平均工资
  3. 查询各岗位平均薪资大于10000且小于20000的岗位名、平均工资
答案
 
1. select post,group_concat(emp_name) as name,count(id) as sum_id from employee group by post having sum_id < 2;
2. select post,avg(salary) as avg_salary from employee group by post having avg_salary > 10000;
3. 方法一
select post,avg(salary) as avg_salary from employee group by post HAVING avg_salary BETWEEN 10000 and 20000;
方法二
select post,avg(salary) as avg_salary from employee group by post having avg_salary > 10000 and avg_salary < 20000;
    

order by 查询排序

按单列排序:

​ select * from employee order by salary; # 默认升序
​ select * from employee order by salary asc; # 升序查询
​ select * from employee order by salary desc; # 倒序查询

按多列排序:

​ 先按照年龄排序(升序),再按照薪资排序起来(降序)

​ select * from employee order by age, salary desc;

练习
  1. 查询所有员工信息,先按照age升序排序,如果age相同则按照hire_date降序排序
  2. 查询各岗位平均薪资大于10000的岗位名、平均工资,结果按平均薪资升序排列
  3. 查询各岗位平均薪资大于10000的岗位名、平均工资,结果按平均薪资降序排列
答案
 
1. select * from employee order by age asc,hire_date desc;
2. select post,avg(salary) as avg_salary from employee group by post having avg_salary > 10000 order by avg_salary asc; 
3. select post,avg(salary) as avg_salary from employee group by post having avg_salary > 10000 order by avg_salary desc;

LIMIT 限制查询的记录数

示例:

​ # 默认初始位置为0,查询出从0开始到第3条;

​ select * from employee order by salary desc limit 3;

​ # 从第0条开始,既先查询出第一条,然后饱含这一条在内往后查询5条

​ select * from employee order by salary desc limit 1,5;

​ # 从第五条开始,既先查询第6条,然后饱含这一条在内往后查5条

​ select * from employee order by salary desc limit 5,5;

练习
  1. 分页显示,每页5条
答案
 
1. select * from employee limit 5;
2. select * from employee limit 5,5;
3. select * from employee limit 10,5;

使用正则表达式查询

select * from employee where emp_name regexp '^al';

select * from employee where emp_name regexp 'on$';

select * from employee where emp_name regexp '丫{1}';

小结:对字符串匹配的方式
WHERE emp_name = 'egon';
WHERE emp_name LIKE 'yua%';
WHERE emp_name REGEXP 'on$';

练习

查看所有员工中名字是jin开头,n或者g结果的员工信息

答案
 
1.select * from employee where emp_name regexp '^jin.*[ng]$';

多表查询

建表与数据准备

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

create table empy(
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 empy(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 |
+----+------------+--------+------+--------+

查询语法

重点: 外链接语法

​ select 字段列表 from 表1 inner|left|right join 表二 on 表1.字段 = 表2.字段;

1 交叉链接: 不适用与任何匹配条件.生成笛卡尔积
select * from empy,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 | 运营         |
+----+------------+--------+------+--------+------+--------------+
24 rows in set (0.00 sec)

2 内连接:只连接匹配的行
# 找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出正确的结果
# department没有204这个部门,因而empy表中关于204这条员工的信息没有匹配出来

mysql> select empy.id,empy.name,empy.age,empy.sex,department.name from empy inner join department on empy.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   | 技术         |
+----+-----------+------+--------+--------------+
5 rows in set (0.00 sec)

# 上述sql等价于
select empy.id,empy.name,empy.age,empy.sex,department.name from empy,department where empy.dep_id = department.id;

3 外链接之左外连接:优先显示左表全部记录
# 以左表为准,既找出所有员工信息,当然包括没有部门的员工
# 本质就是: 在内连接的基础上增加左边有右边没有的结果

mysql> select empy.id,empy.name,department.name from empy left join department on empy.dep_id = department.id;
+----+------------+--------------+
| id | name       | name         |
+----+------------+--------------+
|  1 | egon       | 技术         |
|  5 | liwenzhou  | 技术         |
|  2 | alex       | 人力资源     |
|  3 | wupeiqi    | 人力资源     |
|  4 | yuanhao    | 销售         |
|  6 | jingliyang | NULL         |
+----+------------+--------------+
6 rows in set (0.00 sec)

4 外连接之右外连接: 优先显示右表全部记录
# 以右表为准,既查找出所有部门信息,包括没有员工的部门
# 本质就是: 在内链接的基础上增加右边有左边没有的结果

mysql> select empy.id,empy.name,department.name from empy right join department on empy.dep_id = department.id;
+------+-----------+--------------+
| id   | name      | name         |
+------+-----------+--------------+
|    1 | egon      | 技术         |
|    2 | alex      | 人力资源     |
|    3 | wupeiqi   | 人力资源     |
|    4 | yuanhao   | 销售         |
|    5 | liwenzhou | 技术         |
| NULL | NULL      | 运营         |
+------+-----------+--------------+
6 rows in set (0.00 sec)

5 全外连接:显示左右两个表全部记录
# 全外连接: 在内连接的基础上增加左边有右边没有的 和 右边有左边没有的结果 
# 注意: mysql不支持全外连接  full join
# 强调: mysql可以使用此种方法间接实现全外连接

mysql> select * from empy left join department on empy.dep_id = department.id union select * from empy right join department on empy.dep_id = department.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)

符合条件连接查询
# 示例1:以内连接的方式查询employee和department表,并且employee表中的age字段值必须大于25,即找出年龄大于25岁的员工以及员工所在的部门
1. select empy.name,empy.age,empy.dep_id,department.id,department.name as de_name from empy inner join department on empy.age > 25 and empy.dep_id = department.id;
2. select empy.name,empy.age,empy.dep_id,department.id,department.name as de_name from empy inner join department on empy.dep_id = department.id where empy.age > 25;

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

1. select * from empy inner join department on empy.dep_id = department.id where age > 25 order by age asc;

子查询

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

1 带IN关键字的子查询
# 查询平均年龄在25岁以上的部门名

SELECT
	id,
	department.NAME AS de_name 
FROM
	department 
WHERE
	id IN ( SELECT dep_id FROM empy GROUP BY dep_id HAVING avg( age ) > 25 )

#查看技术部员工姓名

SELECT NAME 
FROM
	empy 
WHERE
	dep_id IN ( SELECT id FROM department WHERE NAME = '技术' );

#查看不足1人的部门名(子查询得到的是有人的部门id)	

select name from department where id not in (select dep_id from empy);
select name from department where id not in (select distinct dep_id from empy);

2 带比较运算符的子查询
# 比较运算符: > < = >= <= != <>

# 查询大于所有人平均年龄的员工名和年龄
mysql> select name,age from empy where age > (select avg(age) from empy);
+---------+------+
| name    | age  |
+---------+------+
| alex    |   48 |
| wupeiqi |   38 |
+---------+------+
2 rows in set (0.00 sec)

# 查询大于部门内平均年龄的员工名、年龄
SELECT
	t1.NAME,
	t1.age 
FROM
	empy AS t1
	INNER JOIN ( SELECT dep_id, avg( age ) AS avg_age FROM empy GROUP BY dep_id ) AS t2 ON t1.dep_id = t2.dep_id 
WHERE
	t1.age > t2.avg_age;

3 带EXISTS关键字的子查询

EXISTS 关键字表示存在. 在使用EXISTS关键字时,内层查询语句不返回查询的记录.

而是返回一个真假值. True或False

当返回True时,外层查询语句将进行查询;当返回为False时,外层语句不进行查询

# department表中存在dept_id=203,
# Ture  外层查询开始执行
# False 外层查询不执行

mysql> select * from empy where exists (select id from department where id = 203);
+----+------------+--------+------+--------+
| 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)

mysql> select * from empy where exists (select id from department where id = 288);
Empty set (0.00 sec)

练习: 查询每个部门最新入职的那位员工
create table empy2(
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
);

insert into empy2(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)
;

答案一
 
SELECT
	* 
FROM
	empy2 AS t1
	INNER JOIN ( SELECT post, max( hire_date ) AS max_date FROM empy2 GROUP BY post ) AS t2 ON t1.post = t2.post 
WHERE
	t1.hire_date = t2.max_date;
答案二
 
SELECT
	t3.NAME,
	t3.post,
	t3.hire_date 
FROM
	empy2 AS t3 
WHERE
	id IN (
SELECT
	( SELECT id FROM empy2 AS t2 WHERE t2.post = t1.post ORDER BY hire_date DESC LIMIT 1 ) 
FROM
	empy2 AS t1 
GROUP BY
	post 
	);

答案一为正确答案,答案二中的limit 1有问题(每个部门可能有>1个为同一时间入职的新员工),我只是想用该例子来说明可以在select后使用子查询

可以基于上述方法解决:比如某网站在全国各个市都有站点,每个站点一条数据,想取每个省下最新的那一条市的网站质量信息

posted @ 2019-12-03 15:49  Anesthesias  阅读(254)  评论(0编辑  收藏  举报