MySQL基础

认识数据库

数据库的相关概念

数据库的好处:

  • 实现数据持久化到本地

  • 使用完整的管理系统统一管理,易于查询

数据库的概念:

  • DB:数据库(database);存储数据的“仓库,它保存了一系列有组织的数据。

  • DBMS:数据库管理系统(Database Management System);数据库是通过DBMS创建和操作的容器。

  • SQL:结构化查询语句(Structure Query Language);专门用来与数据库通信的语言。

    ​ 不是某个数据库软件特有的,而是几乎所有的主流数据库软件通用的语言。

数据库存储数据的特点:

  1. 将数据放到表中,表在放到库中。
  2. 一个数据库中可以有多个表,每个表都有一个名字,用来标识自己。表名具有唯一性。
  3. 表具有一些特性,这些特性定义了数据在表中如何存储,类似Java中“类”的设计。
  4. 表由列组成,他们也称为字段。所有表都是由一个或多个列组成的,每一列类似Java中的“属性”。
  5. 表中的数据是按行存储的,每一行类似Java中的“对象”。

常见的数据库管理系统:

  • MySQL、Oracle、DB2、SqlServer等

MySQL的介绍

MySQL的背景:

  • 前身属于瑞典的一家公司,MySQL AB
  • 08年被sun公司收购
  • 09年sun公司被oracle公司收购

MySQL产品的特点:

  • 成本低:开放源代码
  • 性能高:执行很快
  • 体积小:很容易安装和使用

SQL的优点:

  1. 不是某个特定数据库供应商专有语言,几乎所有DBMS都支持SQL。
  2. 简单易学
  3. 虽然简单,但实际上是一种强有力的语言,灵活使用其语言元素,可以进行非常复杂和高级的数据库的操作。

MySQL的下载安装、配置与使用

MySQL的下载:

https://dev.mysql.com/downloads/mysql/5.5.html#downloads

MySQL服务的启动和停止:

  1. 右击开始→计算机管理→服务和应用程序→服务
  2. 以管理员身份运行命令提示符
    • 停止:net stop mysql
    • 启动:net start mysql

MySQL服务端的登陆和退出:

登陆之前确保服务是启动的!

  1. 登陆:登陆之前确保服务是启动的!

    • 命令提示符 -h主机名 -P端口号 -u用户名 -p密码 (p和密码之间不能有空格)

      mysql -h localhost -P 3306 -u root -p

      mysql -hlocalhost -P3306 -uroot -p

    • 开始菜单→MySQL客户端(只限于root用户)

  2. 退出:exit 或 Ctrl+C

MySQL的常见命令

  1. 查看当前所有的数据库 show databases;

  2. 打开指定的库 use 库名;

  3. 查看当前库的所有表 show tables;

  4. 查看其它库的所有表 show tables from 库名;

    例:

    1
    2
    3
    4
    5
    use test;
    show tables;
    show tables from mysql;

    #此时依然在test库里,仅仅是查看了mysql里的表,而没有出去
  5. 查看当前所在库 show database();

  6. 创建表

    1
    2
    3
    4
    5
    create table 表名(
    列名 列类型,
    列名 列类型,
    ...
    );
  7. 查看表结构 desc 表名;

  8. 查看表中数据 select * from 表名;

  9. 查看当前数据库的版本

    方式一:登录到MySQL服务端

    select version()

    方式二:没有登录到MySQL服务端

    mysql --version 或者 mysql -V

MySQL语法规范

  1. 不区分大小写,但建议关键字大写,表名、列名小写
  2. 每行命令最好用分号结尾
  3. 每条命令根据需要,可以进行缩进或换行
  4. 注释
    1. 单行注释:#注释文字 或者– 注释文字(–后面必须加空格)
    2. 多行注释:/*注释文字*/

DQL语言的学习

基础查询

特点

  1. 查询列表可以是:表中的字段、常量值、表达式、函数
  2. 查询的结果是一个虚拟的表格

语法

​ select 查询列表 from 表名;

​ 查询前先打开数据库 use myemployees;

  1. 查询表中的单个字段 select last_name from employees;

  2. 查询表中多个字段 select last_name,salary,email,from employees;

  3. 查询表中的所有字段 select * from employees;

  4. 查询常量值 select 100; select 'john';

  5. 查询表达式 select 100*98;

  6. 查询函数 select verson();

  7. 为字段起别名

    • 好处:1、便于理解

    ​    2、如果要查询的字段有重名的情况,使用别名可以区分开来

    • 方式一:使用as

      select last_name as 姓,first_name as 名 from employees;

    • 方式二:使用空格

      select last_name 姓,first_name 名 from employees;

    • 案例:查询salary,显示结果为 out put

      • select salary as 'out put' from employees;

        当别名中有空格、#等特殊符号时,用引号括起来

  8. 去重

    查询员工表中涉及到的所有的部门编号

    select distinct department_id from employees;

  9. +的作用

    • mysql中+只有一个功能:运算符
    1. 两个操作数都为数值型,则做加法运算 select 100+90;
    2. 其中一方为字符型,试图将字符型数值转换成数值型
      • 如果转换成功,则继续做加法运算 select '123'+90; 结果为213
      • 如果转换失败,则将字符型数值转换成0 select 'john'+90; 结果为90
    3. 只要其中一方为null,则结果肯定为null

    【补充】concat函数   功能:拼接字符

    案例:查询员工名和姓连接成一个字段,并显示为 姓名

    1
    2
    3
    4
    select
    concat(last_name,first_name) as 姓名
    from
    employees

条件查询

语法

1
2
3
4
5
6
7
8
select
查询列表
from
表名
where
筛选条件;

#执行顺序:from——where——select

分类

  1. 按条件表达式筛选
    • 简单的条件运算符:> < = != <> >= <=

    • 案例一:查询工资大于12000的员工信息

      1
      2
      3
      4
      5
      6
      select
      *
      from
      employees
      where
      salary>12000;
    • 案例二:查询部门编号不等于90号的员工名和部门编号

      1
      2
      3
      4
      5
      6
      7
      select
      last_name,
      department_id
      from
      employees
      where
      department_id<>90;
  2. 按逻辑表达式筛选:
    • 逻辑运算符: and or not 作用:用于连接条件表达式

    • 案例一:查询工资在10000到20000之间的员工名、工资以及奖金

      1
      2
      3
      4
      5
      6
      7
      8
      select
      last_name,
      salary,
      commission_pct
      from
      employees
      where
      salary>=10000 and salary<=20000;
    • 案例二: 查询部门编号不是在90到110之间,或者工资高于150000的员工信息

      1
      2
      3
      4
      5
      6
      select
      *
      from
      employees
      where
      not(department_id>=90 and department_id<=110) or salary>15000;
  3. 模糊查询
    • like

      • 特点:一般和通配符搭配使用

        通配符:

        ​ %表示任意多个字符,包含0个字符

        ​ _表示任意单个字符

      案例一:查询员工名中包含字符a的员工信息

      1
      2
      3
      4
      5
      6
      select
      *
      from
      employees
      where
      last_name like '%a%';

      案例二:查询员工名中第三个字符为e,第五个字符为a的员工名和工资

      1
      2
      3
      4
      5
      6
      7
      select
      last_name,
      salary
      from
      employees
      where
      last_name like '__e_a%';

      案例三:查询员工名中第二个字符为_的员工名

      1
      2
      3
      4
      5
      6
      select
      last_name,
      from
      employees
      where
      last_name like '_\_%';
    • between and

      • 可以提高语句简洁度
      • 包含两个临界值
      • 两个临界值不要调换顺序

      案例:查询员工编号在100到120之间的员工信息

      1
      2
      3
      4
      5
      6
      select
      *
      from
      employees
      where
      employee_id between 100 and 120;
    • in

      • 含义:判断某字段的值是否属于in列表中的某一项
      • 特点:
        1. 使用in提高了语句简洁度
        2. in列表的值必须一致或兼容
        3. 不能包含_和%

      案例:查询员工的工种编号是IT_PROT,AD_VP,AD_PRES中的一个员工名和工种编号

      1
      2
      3
      4
      5
      6
      7
      select
      last_name,
      job_id
      from
      employees
      where
      job_id in('IT_PROT','AD_VP','AD_PRES');
    • is null

      • =或<>不能用于判断null值,is null 或 is not null可以判断null值

      案例一:查询没有奖金的员工名和奖金率

      1
      2
      3
      4
      5
      6
      7
      select
      last_name,
      commission_pct
      from
      employees
      where
      commission_pct is null;
    • 安全等于 <=>

      • is null 仅可以判断null值
      • <=>既可以判断null值,又可以判断普通的值,可读性较低

      案例一:查询没有奖金的员工名和奖金率

      1
      2
      3
      4
      5
      6
      7
      select
      last_name,
      commission_pct
      from
      employees
      where
      commission_pct is null;

      案例二:查询工资为12000的员工信息

      1
      2
      3
      4
      5
      6
      7
      select
      last_name,
      salary
      from
      employees
      where
      salary <=> 12000;

    【补充】ifnull函数

    ​ ifnull(commission_pct,0) 如果commission_pct值为null,则值为0

    案例:查询员工号为176的员工的姓名、部门号和年薪

    1
    2
    3
    4
    5
    6
    7
    8
    select
    last_name,
    department_id,
    salary*12*(1+iffnull(commission_pct,0)) as 年薪
    from
    employees
    wwhere
    employee_id =176;

    【补充】isnull函数

    ​ 功能:判断某字段或表达式是否为null,如果是返回为1,否则返回0

    1
    2
    3
    4
    select 
    isnull (commission_pct)
    from
    employees;
    经典面试题

    试问:select*from employees;

    select * from employees where commission_pct like '%%' and last_name like '%%'

    结果是否一样?并说明原因

    不一样!如果判断的字段有null值,结果就不一样;如果没有null值,结果就一样

排序查询

语法

1
2
3
4
5
6
7
8
9
10
select
查询列表
from
表名
where
筛选条件
order by
排序列表 asc/desc;

#执行顺序:from——where——select——order by

特点

  1. asc代表的是升序,desc代表的是降序;如果不写默认是升序
  2. order by 子句中可以支持单个字段、多个字段、表达式、函数、别名
  3. order by 子句一般是放在查询语句的最后面,limit子句除外

案例一:查询员工信息,要求按工资排序

1
2
3
select * from employees order by salary desc;	#从高到低
select * from employees order by salary asc; #从低到高
select * from employees order by salary; #从低到高

案例二:【添加筛选条件】查询部门编号大于等于90的员工信息,按入职时间的先后顺序排序

1
2
3
4
5
6
7
8
select
*
from
employees
where
department_id>=90
order by
hiredate asc;

案例三:【按表达式排序】按年薪的高低显示员工的信息和年薪

1
2
3
4
5
6
7
select
*,
salary*12*(1+ifnull(commission_pct,0)) as 年薪
from
employees
order by
salary*12*(1+ifnull(commission_pct,0)) desc;

案例四:【按别名排序】按年薪的高低显示员工的信息和年薪

1
2
3
4
5
6
7
select
*,
salary*12*(1+ifnull(commission_pct,0)) as 年薪
from
employees
order by
年薪 desc;

案例五:【按函数排序】按姓名的长度显示员工的姓名和工资

1
2
3
4
5
6
7
8
select
length(last_name) as 字节长度,
last_name,
salary
from
employees
order by
length(last_name) desc;

案例六:【按多个字段排序】查询员工信息,要求先按工资升序,再按员工编号降序

1
2
3
4
5
6
7
select
*
from
employees
order by
salary asc,
employee_id desc;

常见函数

概念:类似于Java中的方法,将一组逻辑语句封装在方法体中,对外暴露方法名

好处:

  1. 隐藏了细节
  2. 提高代码的重用性

调用:select函数名(实参列表);

特点:

  1. 叫什么(函数名)
  2. 干什么(函数功能)

分类:

  1. 单行函数:如 concat、length、ifnull等
  2. 分组函数:做统计使用,又称为统计函数、聚合函数、组函数

单行函数

字符函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#1、length	获取参数值的字节个数
select length ('john') #返回值4
select length ('张三丰hahaha') #返回值15

#2、concat 拼接字符串
select concat(last_name,'_',first_name) 姓名 from employees;

#3、upper、lower
select upper('john'); #返回值JOHN
select lower('joHn'); #返回值john
#案例:将姓变大写,名变小写,然后拼接
select concat(upper(last_name),lower(first_name)) 姓名 from employees;

#4、substr(substring)
/*
注意:索引从1开始
*/

#截取从指定索引处后面所有字符
select substr ('李莫愁爱上了陆展元'7) out_put; #陆展元

#截取从指定索引处指定字符长度的字符
select substr ('李莫愁爱上了陆展元'13) out_put; #李莫愁

#案例:姓名中首字符大写,其他字符小写,然后用_拼接,显示出来
select concat(upper(substr(last_name,1,1)),'_',lower(substr(last_name,2))) out_put from employees;

#5、instr 返回子串第一次出现的索引,如果找不到返回0
select instr('杨不悔爱上了殷六侠','殷六侠') #7
select instr('杨不殷六侠悔爱上了殷六侠','殷六侠') #3
select instr('杨不悔爱上了殷六侠','殷八侠') #0

#6、trim
select length(trim(' 张翠山 ')) as out_put; #9
select trim('a' from 'aaaaaa张a翠a山aaaaa') as out_put; #张a翠a山

#7、lpad 用指定的字符实现左填充指定长度
select lpad('殷素素',10,'*') as out_put; #*******殷素素
select lpad('殷素素',,'*') as out_put; #殷素

#8、rpad 用指定的字符实现右填充指定长度
select rpad('殷素素',12,'ab') as out_put; #殷素素ababababa

#9、replace替换
select replace('张无忌爱上了周芷若','周芷若','赵敏') as out_put; #张无忌爱上了赵敏
select replace('周芷若张无忌爱上了周芷若','周芷若','赵敏') as out_put; #赵敏张无忌爱上了赵敏
数学函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#round 四舍五入

select round(1.65); #2
select round(1.567,2); #2


#ceil 向上取整,返回大于等于该参数的最小整数

select ceil(1.002); #2
select ceil(1.00); #1
select ceil(-1.02); #-1


#floor 向下取整,返回小于等于该参数的最大整数

select floor(9.99); #9
select floor(-9.99); #-10


#truncate 截断

select truncate(1.69,1); #1.6


#mod 取余

mod(a,b): a-a/b*b

select mod(10,3); #1
select mod(-10,-3); #-1
select mod(-10,3); #-1
select mod(10,-3); #1

#rand 获取随机数返回0-1之间的小数
日期函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#now 返回当前系统日期+时间
select now();

#curdate 返回当前系统日期,不包含时间
select curdate();

#curtime 返回当前时间,不包含日期
select curtime();

#可以获取指定的部分,年、月、日、小时、分钟、秒
select year(now()) 年;
select year('1998-1-1') 年;
select year(hiredate)年 from employees;
select month(now()) 月;
select monthname(now()) 月; #返回英文月份

#str_to_date 将字符通过指定的格式转换成日期
select str_to_date('1998-3-2','%Y-%c-%d') as out_put;

#查询入职日期为1992-4-3的员工信息
select * from employees where hiredate = '1992-4-3';

select * from employees where hiredate = str_to_date('4-3 1992','%c-%d %Y');

#date_format 将日期转换成字符
select date_format(now(),'%y年%m月%d日') as out_put;

#查询有奖金的员工名和入职日期(xx月/xx日 xx年)
select last_name,date_format(hiredate,'%m月/%d日 %y年') 入职日期
from employees
where commission_pct is not null;

#datediff 返回两个日期相差的天数

#monthname 以英文形式返回月
序号 格式符 功能
1 %Y 四位的年份
2 %y 两位的年份
3 %m 月份(01,02…11,12)
4 %c 月份(1,2,…11,12)
5 %d 日(01,02,…)
6 %H 小时(24小时制)
7 %h 小时(12小时制)
8 %i 分钟(00,01…59)
9 %s 秒(00,01,…59)
其他函数
1
2
3
4
5
select version();	#当前数据库服务器的版本
select database(); #当前打开的数据库
select user(); #当前用户
select password('字符'); #返回该字符的密码形式
select md5('字符'); #返回该字符的md5加密形式
流程控制函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#1. if 函数:if else效果
select if(10<5,'大''小');

select last_name,commission_pct,if(commission_pct is null,'没奖金','有奖金') 备注
from employees;

#2. case函数的使用一:switch case 的效果
/*
java中
switch(变量或表达式){
case 常量1:语句1;break;
...
default:语句n;break;
}

mysql中
case 要判断的字段或表达式
when 常量1 then 要显示的值1或语句1;
when 常量2 then 要显示的值2或语句2;
...
else 要显示的值n或语句n;
end
*/

/*
案例:查询员工的工资,要求:
部门号=30,显示的工资为1.1倍
部门号=40,显示的工资为1.2倍
部门号=50,显示的工资为1.3倍
其他部门,显示的工资为原工资
*/
select salary 原始工资,department_id,
case department_id
when 30 then salary*1.1
when 40 then salary*1.2
when 50 then salary*1.3
else salary
end as 新工资
from employees;

#3. case函数的使用二:类似于多重if
/*
java中
if (条件1){
语句1;
}else if(条件2){
语句2;
}
...
else{
语句n;
}

mysql中
case
when 条件1 then 要显示的值1或语句1;
when 条件2 then 要显示的值2或语句2;
...
else 要显示的值n或语句n;
end
*/

/*
案例:查询员工的工资情况
如果工资>20000,显示A级别
如果工资>15000,显示B级别
如果工资>10000,显示C级别
否则,显示D级别
*/
select salary,
case
when salary>20000 then 'A'
when salary>15000 then 'B'
when salary>10000 then 'C'
else 'D'
end as 工资级别
from employees;

分组函数

功能

用作统计使用,又称为聚合函数或统计函数或组函数

分类

​ sum 求和、avg 平均值、max 最大值、min 最小值、count 计算个数

特点
  1. sum、avg一般用于处理数值型

    max、min、count可以处理任何类型

  2. 以上分组函数都忽略null值

  3. 可以和distinct搭配实现去重的运算

  4. count函数的单独介绍

    一般使用count(*)用作统计行数

  5. 和分组函数一同查询的字段要求是group by后的字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#1.简单的使用
select sum(salary) from employees;
select avg(salary) from employees;
select max(salary) from employees;
select min(salary) from employees;
select count(salary) from employees;

select sum(salary) 和,round(avg(salary),2) 平均,max(salary) 最高,min(salary) 最低,count(salary) 个数
from employees;

#3.可以和distinct搭配实现去重的运算
select sum(distinct salary),sum(salary) from employees;
select count(distinct salary),count(salary) from employees;

#4.count 函数的具体介绍
select count(salary) from employees;
select count(*) from employees;
select count(1) from employees;

分组查询

语法

1
2
3
4
5
6
7
8
9
10
11
/*
select 分组函数,列(要求要求出现在group by 的后面)
from表
[where 筛选条件]
group by 分组的列表
[order by 子句]

注意:查询列表必较特殊,要求是分组函数group by 后面出现的字段


*/

特点

  1. 分组查询中筛选条件分为两类

    数据源 位置 关键字
    分组前筛选 原始表 group by 子句的前面 where
    分组后筛选 分组后的结果集 group by 子句的后面 having

    ①分组函数做条件肯定是放在having子句中

    ②能用分组前筛选的,就优先考虑分组前筛选

  2. group by 子句支持单个字段分组,多个字段分组(多个字段用逗号隔开没有顺序),表达式或函数(用的较少)

  3. 也可以添加排序(排序放在整个分组查询的最后)

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#简单的分组查询

#案例1;查询每个工种的最高工资
select max(salary),job_id
from employees
group by job_id;

#案例2;查询每个位置上的部门个数
select count(*),location_id
from departments
group by location_id;

#添加分组前筛选条件

#案例1;查询邮箱中包含a字符的,每个部门的平均工资
select avg(salary),department_id
from employees
where email like '%a%'
group by department_id;

#案例2;查询有奖金的每个领导手下员工的最高工资
select max(salary),manager_id
from employees
where commission_pct is not null
group by manager_id;

#添加分组后的筛选条件

#案例1;查询哪个部门的员工个数大于2

#①查询每个部门的员工个数
select count(*),department_id
from employees
group by department_id
#②根据①的结果进行筛选,查询哪个部门员工个数大于2
select count(*),department_id
from employees
group by department_id
having count(*)>2;

#案例2;查询每个工种有奖金的员工的最高工资>12000的工种编号和最高工资

#①查询每个工种有奖金的员工的最高工资
select max(salary),job_id
from eemployees
where commission_pct is not null
group by job_id;

#②根据①结果继续筛选,最高工资>12000
select max(salary),job_id
from eemployees
where commission_pct is not null
group by job_id
having max(salary)>12000;

#案例3;查询领导编号>102的每个领导手下的最低工资>5000的领导编号是哪个,以及其最低工资

#①查询每个领导手下的员工的最低工资
select min(salary),manager_id
from employees
group by manager_id
#②添加筛选条件:编号>102
select min(salary),manager_id
from employees
where manager_id>102
group by manager_id
#③添加筛选条件:最低工资>5000
select min(salary),manager_id
from employees
where manager_id>102
group by manager_id
having min(salary>5000);

#按表达式或函数分组

#案例:按员工姓名的长度分组,查询每一组的员工个数,筛选员工个数>5的有哪些
#①
select count(*),length(last_name) len_name
from employees
group by length(last_name);
#②添加筛选条件
select count(*),length(last_name) len_name
from employees
group by length(last_name)
having count(*)>5;

#按多个字段分组

#案例:查询每个部门每个工种的员工的平均工资
select avg(salary),department_id,job_id
from employees
group by department_id,job_id;

#添加排序

#案例:查询每个部门每个工种的员工的平均工资,并且按平均工资的高低显示
select avg(salary),department_id,job_id
from employees
where department_id is not null
group by department_id,job_id;
order by avg(salary) desc;

连接查询

含义

连接查询又称多表查询,当查询的字段来自多个表时,就会用到多表查询

笛卡尔积

现象:表1有m行,表2有n行,,结果=m*n行

发生原因:没有有效的连接条件

如何避免:添加有效的连接条件

分类

按年代分类
  • sql92标准:仅仅支持内连接,也支持一部分外连接(用于oracle、sqlserver)
  • sql99标准【推荐】:支持内连接+外连接(左外和右外)+交叉连接
按功能分类
  • 内连接
    • 等值连接
    • 非等值连接
    • 自连接
  • 外连接
    • 左外连接
    • 右外连接
    • 全外连接(mysql不支持)
  • 交叉连接

一、sql92标准

等值连接

语法

1
2
3
4
5
6
7
8
9
/*
select 查询列表
from 表1 别名,表2 别名
where 表1.key=表2.key
[and 筛选条件]
[group by 分组字段]
[having 分组后的筛选]
[order by 排序字段]
*/

①多表等值连接的结果为多表的交集部分
②n表连接,至少需要n-1个连接条件
③多表的顺序没有要求
④一般需要为多表起别名
⑤可以搭配前面介绍的所有子句使用,比如排序、分组、筛选

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#1.等值连接
#案例1:查询女神名和对应的男神名
select NAME,boyName
from boys,beauty
where beauty.boyfriend_id=boys.id

#案例2:查询员工名和对应的部门名
select last_name,department_name
from employees,departments
where employees.department_id=departments.department_id;

#2.为表起别名
/*
提高语句的简洁度
区别多个重名的字段

注意:如果为表起了别名,则查询的字段就不能用原来的表名去限定
*/
#案例:查询员工名、工种号、工种名
select last_name,e.job_id,job_title
from employees e,jobs j
where e.job_id=j.job_id;

#3.两个表的顺序可以调换
#案例:查询员工名、工种号、工种名
select last_name,e.job_id,job_title
from jobs j,employees e
where e.job_id=j.job_id;

#4.可以加筛选
#案例1:查询有奖金的员工名、部门名
select last_name,department_name,commission_pct
from employees e,department d
where e.department_id=d.department_id
and e.commission_pct is not null;

#案例2:查询城市名中第二个字符为o的部门名和城市名
select department_name,city
from departments d,locations l
where d.location_id=l,location_id
and city like '_o%';

#5.可以加分组
#案例1:查询每个城市的部门个数
select count(*) 个数,city
from departments d,location l
where d.location_id=l.location
group by city;

#案例2:查询有奖金的每个部门的部门名和部门的领导编号和该部门的最低工资
select department_name,d.manager_id,min(salary)
from departments d,employees e
where d.department_id=e.department_id
and commission is not null
group by department_name,d.manager_id;

#6.可以加排序
#案例:查询每个工种的工种名和员工的个数,并且按员工个数排序
select job_title,count(*)
from employees e,jobs j
where e.job_id=j.job_id
group by job_title
order by count(*) desc;

#7.可以实现三表连接
#案例:查询员工名、部门名和所在城市
select last_name,department_name,city
from employees e,departments d,locations l
where e.department_id=d.department_id
and d.location_id=l.location_id;
非等值连接
1
2
3
4
5
6
7
8
9
10
11
#非等值连接
#案例1:查询员工的工资和工资级别
select salary,grade_level
from employees e,job_grades g
where salary between g.lowest_sal and g.highest_sal;

#案例2:查询工资级别为A的员工工资
select salary,grade_level
from employees e,job_grades g
where salary between g.lowest_sal and g.highest_sal
and g.grade_level='A';
自连接
1
2
3
4
#案例:查询员工名和上级的名称
select e.employee_id,e.last_name,m.employee_id,m.last_name
from employees e,employees m
where e.manager_id=m.employee_id;

二、sql99标准

语法
1
2
3
4
select 查询列表
from1 别名
[连接类型] join2 别名
on 连接条件
内连接
语法
1
2
3
4
5
6
7
8
9
select 查询列表
from1 别名
inner join2 别名
on 连接条件
where 筛选条件
group by 分组列表
having 分组后的筛选
order by 排序列表
limit 子句
特点
  1. 可以添加排序、分组、筛选
  2. inner可以省略
  3. 筛选条件放在where后面,连接条件放在on后面,提高分离性,便于阅读
  4. inner join连接和sql92语法中的等值连接效果是一样的,都是查询多表的交集
  5. 表的顺序可以调换
  6. 内连接的结果=多表的交集
  7. n表连接至少需要n—1个连接条件
分类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#1.等值连接

#案例1:查询员工名、部门名
select last_name,department_name
from employees e
inner join departments d
on e.department_id=d.department_id;

#案例2:查询名字中包含e的员工名和工种名(添加筛选)
select last_name,job_title
from employees e
inner joim jobs j
on e.job_id=j.job_id
where e.last_name like '%e%';

#案例3:查询部门个数>3的城市名和部门个数(添加分组+筛选)
select city,count(*) 部门个数
from departments d
inner join locations
on d.location_id=l.location_id
group by city
having count(*)>3;

#案例4:查询哪个部门的员工个数>3的部门名和员工个数,并按个数降序(添加排序)
select count(*) 个数,department_name
from employees e
inner join departments d
on e.department_id=d.department_id
group by department_name
having count(*)>3
order by count(*) desc;

#案例5:查询员工名、部门名、工种名,并按部门名降序(三表连接)
select last_name,department_name,job_title
from employees e
inner join departments d on e.department_id=d.department_id
inner join jobs j on e.job_id=j.job_id
order by department_name desc;

#2.非等值连接

#案例1:查询员工的工资级别
select salary,grade_level
from employees e
inner join job_grades g
on e.salary between g.lowest_sal and g.highest_sal;

#案例2:查询工资级别的个数>20的个数,并且按工资级别降序
select count(*),grade_level
from employees e
inner join job_grades g
on e.salary between g.lowest_sal and g.highest_sal
group by grade_level
having count(*)>20
order by grade_level desc;

#3.自连接

#案例1:查询员工的名字,上级的名字
select e.last_name,m.last_name
from employees e
inner join employees m
on e.manager_id=m.employee_id;

#案例2:查询姓名中包含字符k的员工的名字,上级的名字
select e.last_name,m.last_name
from employees e
inner join employees m
on e.manager_id=m.employee_id
where e.last_name like '%k%';
外连接
应用场景

用于查询一个表中有,另一个表没有的记录

特点
  1. 外连接的查询结果为主表中的所有记录

    如果从表中有和他匹配的,则显示匹配的值

    如果从表中没有和他匹配的,则显示null

    外连接查询结果=内连接结果+主表中有而从表中没有的记录

  2. 左外连接,lift outer join左边的是主表

    右外连接,right outer join右边的是主表

  3. 左外和右外交换两个表的顺序,可以实现同样的效果

  4. 一般用于查询除了交集部分剩余的不匹配的行

  5. 全外连接full outer join=内连接的结果+表1中有但表2中没有的+表2中有但表1中没有的(MySQL不支持)

案例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#案例1:查询哪个部门没有员工

#左外
select d.*,e.employee_id
from departments d
left outer join employees e
on d.department_id=e.department_id
where e.employee_id is null;

#右外
select d.*,e.employee_id
from employees e
left outer join departments d
on d.department_id=e.department_id
where e.employee_id is null;

交叉连接
1
2
3
4
select b.*,bo.*
from beauty b
cross join boys bo;
#就是使用sql99语法实现的笛卡尔积

子查询

概念

出现在其他语句内部的select语句,称为子查询或内查询

内部嵌套其他select语句的查询,称为外查询或主查询

分类

按子查询出现的位置

select 后面:

​ 仅仅支持标量子查询

from后面:

​ 支持表子查询

where或having后面: ★

​ 标量子查询 (单行)√

​ 列子查询 (多行)√

​ 行子查询

exists后面(相关子查询)

​ 标量子查询

​ 列子查询

​ 行子查询

​ 表子查询

按结果集的行列数不同

标量子查询(结果集只有一行一列)

列子查询(结果集只有一列多行)

行子查询(结果集有一行多列)

表子查询(结果集一般为多行多列)

一、where或having后面

特点
  1. 子查询放在小括号内

  2. 子查询一般放在条件的右侧

  3. 标量子查询,一般搭配着单行操作符(<、>、<=、>=、=、<>)使用

    列子查询,一般搭配着多行操作符(in、any/some、all)使用

  4. 子查询的执行优先于主查询执行,主查询的条件用到了子查询的结果

分类
标量子查询(单行子查询)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#案例1:谁的工资比Abel高?

#①查询Abel的工资
select *
from employees
where last_name='Abel'
#②查询员工的信息,满足salary>①结果
select *
from employees
where salary>(
select *
from employees
where last_name='Abel'
);

#案例2:返回job_id与141号员工相同,salary比143号员工多的员工姓名、job_id和工资

#①查询141号员工的job_id
select job_id
from employees
where employee_id=141
#②查询143号员工的salary
select salary
from employees
where employee_id=143
#③查询员工的姓名,job_id,和工资,要求job_id=①并且salary>
select last_name,job_id,salary
from employees
where job_id=(
select job_id
from employees
where employee_id=141
)and salary>(
select salary
from employees
where employee_id=143
);

#案例3:返回公司工资最少的员工的last_name,job_id和salary

#①查询公司的最低工资
select min(salary)
from employees
#②查询last_name,job_id和salary,要求salary=
select last_name,job_id,salary
from employees
where salary=(
select min(salary)
from employees
);

#案例4:查询最低工资大于50号部门最低工资的部门id和其最低工资

#①查询50号部门的最低工资
select min(salary)
from employees
where department_id=50
#②查询每个部门的最低工资
select min(salary),department_id
from employees
group by department_id
#③在②基础上筛选,满足min(salary)>
select min(salary),department_id
from employees
group by department_id
having min(salary)>(
select min(salary)
from employees
where department_id=50
);

#非法使用标量子查询:子查询结果不是一行一列
列子查询(多行子查询)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#案例1;返回location_id是14001700的部门中的所有员工姓名

#①查询location_id是14001700的部门编号
select distinct department_id
from employees
where location_id in(1400,1700)
#②查询员工姓名,要求部门编号是①列表中的某一个
select last_name
from employees
where department_id in(
select distinct department_id
from employees
where location_id in(1400,1700)
);

#案例2:返回其他工种中比job_id为IT-PROG工种任一工资低的员工的员工号、姓名、job_id以及salary

#①查询job_id为IT-PROG部门的任一工资
select distinct ssalary
from employees
where iob_id='IT-PROG'
#②查询员工号、姓名、job_id以及salary,salary<(①)的任意一个
select last_name,employee_id,job_id,salary
from employees
where salary<any(
select distinct ssalary
from employees
where iob_id='IT_PROG'
)and job_id<>'IT_PROG';
#或
select last_name,employee_id,job_id,salary
from employees
where salary<(
select max (ssalary)
from employees
where iob_id='IT_PROG'
)and job_id<>'IT_PROG';

#案例3:返回其他工种中比job_id为IT-PROG工种所有工资都低的员工的员工号、姓名、job_id以及salary
select last_name,employee_id,job_id,salary
from employees
where salary<all(
select distinct ssalary
from employees
where iob_id='IT_PROG'
)and job_id<>'IT_PROG';
#或
select last_name,employee_id,job_id,salary
from employees
where salary<(
select min (ssalary)
from employees
where iob_id='IT_PROG'
)and job_id<>'IT_PROG';
行子查询(多列多行)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#案例:查询员工编号最小并且工资最高的员工信息

select *
from employees
where (employee_id,salary)=(
select min(employee_id),max(salary)
from employees
);
#——————————————————————————————————————————
#①查询最小的员工编号
select min(employee_id)
from employees
#②查询最高工资
select max(salary)
from employess
#③查询员工信息
select *
from employess
where employee_id=(
select min(employee_id)
from employees
)and salary=(
select max(salary)
from employess
);

二、select 后面

select 后面仅仅支持标量子查询

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#案例1:查询每个部门的员工个数
select d.*,(
select count(*)
from employees e
where e.department_id=d.department_id
)个数
from departments d;

#案例2:查询员工号=102的部门名
select (
select department_name
from departments d
inner join employees e
on d.department_id=e.department_id
where e.employee_id=102
) 部门名;

三、from后面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#案例:查询每个部门的平均工资的工资等级

#①查询每个部门的平均工资
select avg(salary),department_id
from employees
group by department_id
#②连接①的结果集和job_grades表,筛选条件平均工资between lowest_sal and highest_sal
select ag_dep.*,g.grade_level
from (
select avg(salary) ag,department_id
from employees
group by department_id
) ag_dep
inner join job_grades g
on ag_dep.ag between lowest_sal and highest_sal;

四、exists后面

语法:exists(完整的查询语句)

结果:1或0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#案例1:查询有员工的部门名
select department_name
from departments d
where exists(
select *
from employees e
where d.department_id=e.department_id
);

#使用in
select department_name
from departments d
where d.department_id in(
select department_id
from employees
);

分页查询

应用场景

当要显示的数据,一页显示不全,需要分页提交sql请求

特点

  1. limit 语句放在查询语句的最后

  2. 公式

    1
    2
    3
    4
    #要显示的页数page,每页的条目数size
    select 查询列表
    from
    limit (page—1)*size,size;

语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
select 查询列表
from
[
jion type join2
on 连接条件
where 筛选条件
group by 分组字段
having 分组后的筛选
order by 排序的字段
]
limit [offest,]size;

#offest 要显示条目的起始索引(起始索引从0开始)
#size 要显示的条目个数

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
#案例1:查询前五条员工信息
select * from employees limit 0,5;
select * from employees limit 5;

#案例2:查询第十一条到第二十五条员工信息
select * from employees limit 10,15;

#案例3:查询有奖金的员工信息,并且工资较高的前十名显示出来
select *
from employees
where commission_pct is not null
order by salary desc
limit 10;

union联合查询

语法

查询语句1

union

查询语句2

union

应用场景

要查询的结果来自多个表,且多个表没有直接的连接关系,但查询的信息一致时

特点

  1. 要求多条查询语句的查询列数是一致的
  2. 要求多条查询语句的查询的每一列的类型和顺序最好一致
  3. union关键字默认去重,如果使用union all可以包含重复项

案例

1
2
3
4
#案例:查询中国用户中男性信息以及外国用户中男性的用户信息
select id,cname,csex from t_ca where csex='男'
union
select t_id,tname,tGender from t_ua where tGender='male'

DML语言的学习

数据操作语言:

插入:insert

修改:update

删除:delete

一、插入语句

插入语句方式一

语法
1
insert into 表名(列名,...) values(值1,...);
注意事项
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#1.插入的值的类型要与列的类型一致或兼容
insert into beauty(id,name,sex,borndate,phone,photo,boyfriend_id)
values(13,'张三''女','1990-4-23','18988888888',null,2);

#2.不可以为null的列必须插入值,可以为null的列如何插入值?
#方式一:
insert into beauty(id,name,sex,borndate,phone,photo,boyfriend_id)
values(15,'李四''女','1991-4-23','18998888888',null,2);

#方式二:
insert into beauty(id,name,sex,phone)
values(13,'张三''女','18988888888');

#3.列的顺序可以调换
insert into beauty(name,sex,id,phone)
values('王五''男'16'110');

#4.列数的值和个数必须一致
/*
错误写法
insert into beauty(id,name,sex,borndate,phone,photo,boyfriend_id)
values(15,'李四','女','1991-4-23','18998888888',null);
*/

#5.可以省略列名,默认所有列,而且列的顺序和表中列的顺序一致
insert into beauty
values(18,'张飞','男'null,'119',null,null);

插入语句方式二

语法
1
2
insert into 表名
set 列名=值,列名=值,...
案例
1
2
insert into beauty
set id=19,name='赵六',phone='999';

插入语句两种方式比较

  1. 方式一支持插入多行,方式二不支持

    1
    2
    3
    4
    insert into beauty
    values(20,'李华1''女','1991-4-23','18998888888',null,2)
    ,(21,'李华2''女','1991-4-23','18998888888',null,2)
    ,(22,'李华3''女','1991-4-23','18998888888',null,2)
  2. 方式一支持子查询,方式二不支持

    1
    2
    3
    4
    5
    6
    7
    8
    #1
    insert into beauty(id,name,sex,phone)
    select 13,'张三''女','18988888888';

    #2
    insert into beauty(id,name,phone)
    select id,boyfriend,'18988888888'
    from boys where id<3;

二、修改语句

修改单表的记录★

语法
1
2
3
update 表名
set=新值,列=新值...
where 筛选条件
案例
1
2
3
4
5
6
7
#案例1:修改beauty表中姓唐的人的电话为13899999999
update buauty set phone = '13899999999'
where name like '唐%';

#案例2:修改boys表中id为2的名称为张飞,魅力值为10
update boys set boyname='张飞',usercp=10
where id=2;

修改多表的记录[补充]

语法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#sql92语法

update1 别名,表2 别名
set=值,...
where 连接条件
and 筛选条件

#sql99语法

update1 别名
inner|left|right join2 别名
on 连接条件
set=值,...
where 筛选条件
案例
1
2
3
4
5
6
7
8
9
10
11
#案例1:修改张无忌的女朋友手机号为114
update boys bo
inner join beauty b on bo.id=b.boyfriend_id
set b.phone='114'
where bo.boyname='张无忌';

#案例2:修改没有男朋友的女生的男朋友编号都为2
update boys bo
right join beauty b on bo.id=b.boyfriend_id
set b.boyfriend_id=2
where bo.id is null;

三、删除语句

删除语句方式一:delete

语法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#1.单表的删除★
delete from 表名 where 筛选条件;

#2.多表的删除(级联删除) [补充]

#sql92语法:
delete1的别名,表2的别名
from1 别名,表2 别名
where 连接条件
and 筛选条件

#sql99语法:
delete1的别名,表2的别名
from1 别名
inner|left|right join2 别名 on 连接条件
where 筛选条件
案例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#1.单表的删除

#案例:删除手机号以9结尾的女生信息
delete from beauty where phone like '%9';

#2.多表的删除

#案例1:删除张无忌的女朋友的信息
delete b
from beauty b
inner join boys bo on b.boyfriend_id=bo.id
where bo.boyname='张无忌';

#案例2:删除黄晓明的信息以及他女朋友的信息
delete b,bo
from beauty b
inner join boys bo on b.boyfriend_id=bo.id
where bo.boyname='黄晓明';

删除语句方式二:truncate

语法
1
truncate table 表名;

删除语句两种方式的区别[★面试题]

  1. delete可以加where条件,truncate不能加

  2. truncate删除,效率高一丢丢

  3. 假如要删除的表中有自增长列,

    如果用delete删除后,再插入数据,自增长列的值从断点开始,

    而用truncate删除后,再插入数据,自增长列的值从1开始。

  4. truncate删除没有返回值,而delete删除有返回值

  5. truncate删除不能回滚,而delete删除可以回滚

DDL语言的学习

数据定义语言

库和表的管理

创建库、表通用写法:

1
2
3
4
5
drop database if exits 旧库名;
create database 新库名;

drop table if exits 旧表名;
create table 新表名;

一、库的管理

1.库的创建
语法

create database [if not exists] 库名 [character set 字符集];

案例
1
2
#创建库books
create database if not exists books;
2.库的修改

rename database books to 新库名;【该语句已不在使用】

更改库的字符集 alter database books character set gbk;

3.库的删除
语法

drop database [if exists] 库名;

案例
1
2
#删除库books
drop database if exists books;

二、表的管理

1.表的创建
语法
1
2
3
4
5
6
7
create table [if not exists] 表名(
列名 列的类型 [(长度) 约束],
列名 列的类型 [(长度) 约束],
列名 列的类型 [(长度) 约束],
...
列名 列的类型 [(长度) 约束]
);
案例
1
2
3
4
5
6
7
8
#创建表book
create table if not exists book(
id int,#编号
bname varchar(20),#图书名
price double,#价格
authorId int,#作者编号
publishDate datetime#出版日期
);
2.表的修改
  1. 修改列名

    alter table book change column publishdate pubDate datetime;

  2. 修改列的类型或约束

    alter table book modify column pubDate timestamp;

  3. 添加新列

    alter table author add column annual double;

  4. 删除列

    alter table author drop column annual;

  5. 修改表名

    alter table author rename to book_author;

3.表的删除

drop table [if exists] book_author;

4.表的复制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#1.仅仅复制表的结构
create table copy like author;

#2.复制表的结构+数据
create table copy2
select * from author;

#3.只复制部分数据
create table copy3
select id,au_name
from author
where nation='中国';

#4.仅仅复制某些字段
create table copy4
select id,au_name
from author
where 1=2;
#或者
create table copy4
select id,au_name
from author
where 0;

常见数据类型介绍

  • 数值型
    • 整型
    • 小数
      • 定点数
      • 浮点数
  • 字符型
    • 较长的文本
    • 较短的文本
  • 日期型

原则:所选择的类型越简单越好,能保存数值的类型越小越好

一、整型

分类
类型 tinyint smallint mediumint int/integer bigint
字节 1 2 3 4 8
特点
  1. 如果不设置有符号还是无符号,默认是有符号,如果想设置无符号,需要添加unsigned关键字
  2. 如果插入的数值超出了整型的范围,会报out of range异常,并且插入临界值
  3. 如果不设置长度,会有默认的长度,长度代表了显示的最大宽度,如果不够会用0在左边填充,但必须搭配zerofill使用

二、小数

分类
  1. 浮点型
    • float(m,d)
    • double(m,d)
  2. 定点型
    • dec(m,d)
    • decimal(m,d)
特点
  1. m:整数部位+小数部位,d:小数部位,如果超过范围,则插入临界值

  2. m和d都可以省略

    如果是decimal,则m默认为10,d默认为0

    如果是float和double,则会根据插入的数值的精度来决定精度

  3. 定点型的精度较高,如果要求插入数值的精度较高如货币运算等则考虑使用

三、字符型

分类
  • 较短的文本:

​ char

​ varchar

  • 较长的文本:

​ text

​ blob(较大的二进制)

特点
写法 M的意思 特点 空间的耗费 效率
char char(M) 最大的字符数,可以省略,默认为1 固定长度的字符 比较耗费
varchar varchar(M) 最大的字符数,不可以省略 可变长度的字符 比较节省

四、日期型

分类
  • date 只保存日期
  • time 只保存时间
  • year 只保存年
  • datetime 保存日期+时间
  • timestamp 保存日期+时间
特点
字节 范围 时区等的影响
datetime 8 1000—9999 不受
timestamp 4 1970—2038

常见约束

含义:一种限制,用于制表中的数据,为了保证表中数据的准确和可靠性

分类

  1. not null :非空,用于保证该字段的值不能为空

  2. default :默认,用于保证该字段有默认值

  3. primary key : 主键,用于保证该字段的值具有唯一性,并且非空

  4. unique : 唯一,用于保证该字段的值具有唯一性,可以为空

  5. check :检查约束,[mysql中不支持]

  6. foreign key :外键,用于限制两个表的关系,用于保证该字段的值必须来自于主表的关联列的值

    ​ 在从表添加外键约束,用于引用主表中某列的值

添加约束的时机:

  1. 创建表时
  2. 修改表时

约束的添加分类:

  1. 列级约束

    ​ 六大约束语法上都支持,但外键约束没有效果

  2. 表级约束

    ​ 除了非空、默认,其他的都支持

主键和唯一的区别[面试题]

保证唯一性 是否允许为空 一个表中可以有多少个 是否允许组合
主键 × 至多有一个 √ (不推荐)
唯一 可以有多个 √ (不推荐)

外键的特点

  1. 要求在从表设置外键关系
  2. 从表的外键列的类型和主表的关联列的类型要求一致或兼容,名称无要求
  3. 主表的关联列一般是一个key(一般是主键或唯一键)
  4. 插入数据时,先插入主表,再插入从表;删除数据时,先删除从表,再删除主表
1
2
3
4
5
6
#可以通过以下两种方式来删除主表的记录
#级联删除
alter table stuinfo add constraint fk_stu_major foreign key(majorid) references major(id) on delete cascade;

#级联置空
alter table stuinfo add constraint fk_stu_major foreign key(majorid) references major(id) on delete set null;

一、创建表时添加约束

1.添加列级约束

只支持:默认、非空、主键、唯一

1
2
3
4
5
6
7
8
create table stuinfo(
id int primary key,#主键
stuName varchar(20) not null,#非空
gender char(1) check(gender='男' or gender='女'),#检查约束,不支持
seat int unique,#唯一
age int default 18,#默认约束
majorId int references major(id)#外键,列级约束不支持
);
2.添加表级约束
1
2
3
4
5
6
7
8
9
10
11
12
13
create table stuinfo(
id int,
stuName varchar(20),
gender char(1),
seat int,
age int,
majorid int,

[constraint pk] primary key(id),#主键
[constraint uq] unique(seat),#唯一键
[constraint ck] check(gender='男' or gender='女'),#检查约束,不支持
[constraint fk_stuinfo_major] foreign key(majorid) references major(id)#外键
);
通用写法
1
2
3
4
5
6
7
8
9
create table if exists stuinfo(
id int primary key,
stuName varchar(20) not null,
gender char(1),
seat int unique,#唯一
age int default 18,
majorid int,
constraint fk_stuinfo_major foreign key(majorid) references major(id)
);

二、修改表时添加约束

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
drop table if exists stuinfo
create table stuinfo(
id int,
stuname varchar(20),
gender char(1),
seat int,
age int,
majorid int
);

#1.添加非空约束
alter table stuinfo modify column stuname varchar(20) not null;

#2.添加默认约束
alter table stuinfo modify column age int default 18;

#3.添加主键约束
#①列级约束
alter table stuinfo modify column id int primary ley;
#②表级约束
alter table stuinfo add primary key(id);

#4.添加唯一约束
#①列级约束
alter table stuinfo modify column seat int unique;
#②表级约束
alter table stuinfo add unique (seat);

#5.添加外键约束
alter table stuinfo add constraint fk_stuindo_major foreign key(majorid) references major(id);

三、修改表时删除约束

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#1.删除非空约束
alter table stuinfo modify column stuname varchar(20) null;

#2.删除默认约束
alter table stuinfo modify age int;

#3.删除主键约束
alter table stuinfo drop primary key;

#4.删除唯一约束
alter table stuinfo drop index seat;

#5.删除外键约束
alter table stuinfo drop foreign key fk_stuindo_major;

四、标识列

又称为自增长列

含义:可以不用手动的插入值,系统提供默认的序列值

特点:

  1. 标识符必须和主键搭配吗?不一定,但要求是一个key

  2. 一个表可以有几个标识列?至多一个!

  3. 标识符的类型只能是数值型

  4. 标识符可以通过 set auto_increment_increment=3;设置布长

    也可以通过手动插入值,设置起始值

一、创建表时设置标识列
1
2
3
4
5
6
create table tab_identity(
id int primary key auto_increment,
name varchar(20)
);

insert into tab_identity(id,name) values(null,'john');
二、修改表时设置标识列
1
alter table tab_identity modify column id int primary key auto_increment;
三、修改表时删除标识列
1
alter table tab_identity modify column id int primary key;

TCL语言的学习

Transaction Control Language 事务控制语言

事务:一个或一组sql语句组成一个执行单元,这个执行单元要么全部执行,要么全部不执行

事务和事务处理

MySQL中的存储引擎[了解]

  1. 概念:在MySQL中的数据用各种不同的技术存储在文件(或内存)中
  2. 通过show engines; 来查看MySQL支持的存储引擎
  3. 在MySQL中用的最多的存储引擎有:innodb,myisam,memory等。其中innodb支持事务,而myisam、memory等不支持事务

事务的ACID属性[经典面试题]

  1. 原子性(Atomicity)

    原子性是指事务是一个不可分割的工作单位,事务中的操作要么都发生,要么都不发生

  2. 一致性(Consistency)

    事务必须使数据库从一个一致性状态变换到另外一个一致性状态

  3. 隔离性(Isolation)

    事务的隔离性是指一个事务的执行不能被其他事务干扰,即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰

  4. 持久性(Durability)

    持久性是指一个事务一旦被提交,它对数据库中数据的改变就是永久性的,接下来的其他操作和数据库故障不应该对其有任何影响

事务的创建

隐式事务:事务没有明显的开启和结束的标志

​ 比如:insert、update、delete语句

显式事务:事务具有明显的开启和结束的标记

前提:必须先设置自动提交功能为禁用 set autocommit=0;

步骤1:开启事务

set autocommit=0;

start transaction; 可选

步骤2:编写事务中的sql语句(select、insert、update、delete)

语句1;

语句2;

步骤3: 结束事务

commit;提交事务

rollback;回滚事务

1
2
3
4
5
6
7
8
9
10
#演示事务的使用步骤

#开启事务
set autocommit=0;
start transaction;
#编写一组事务的语句
update account set balance=500 where username='张无忌';
update account set balance=1500 where username='赵敏';
#结束事务
commit;

数据库的隔离级别

  • 对于同时运行的多个事务,当这些事务访问数据库中相同的数据时,如果没有采取必要的隔离机制,就会导致各种并发问题:

    • 脏读:对于两个事务T1,T2,T1读取了已经被T2更新但还没有被提交的字段之后,若T2回滚,T1读取的内容就是临时且无效的;
    • 不可重复读:对于两个事务T1,T2,T1读取了一个字段,然后T2更新了该字段之后,T1再次读取同一个字段,值就不同了;
    • 幻读:对于两个事务T1,T2,T1从一个表中读取了一个字段,然后T2在该表中插入了一些新的行之后,如果T1再次读取同一个表,就会多出几行;
  • 数据库事务的隔离性:数据库系统必须具有隔离并发运行各个事务的能力,使它们不会相互影响,避免各种并发问题

  • 一个事务与其他事务隔离的程度称为隔离级别,数据库规定了多种事务隔离级别,不同隔离级别对应不同的干扰程度,隔离级别越高,数据一致性就越好,但并发性越弱

  • 数据库提供的4种事务隔离级别:

隔离级别 描述
READ UNCOMMITTED(读未提交数据) 允许事务读取未被其他事务提交的变更,脏读、不可重复读和幻读问题都会出现
READ COMMITTED(读已提交数据) 只允许事务读取已经被其他事务提交的变更,可以避免脏读,但不可重复读和幻读问题仍然可能出现
REPEATABLE READ(可重复读) 确保事务可以多次从一个字段中读取相同的值,在这个事务持续期间,禁止其他事务对这个字段进行更新,可以避免脏读和不可重复读,但幻读的问题仍然存在
SERIALIZABLE(串行化) 确保事务可以从一个表中读取相同的行,在这个事务持续期间,禁止其他事务对该表执行插入,更新和删除操作,所有并发问题都可以避免,但性能十分低下
  • Oracle支持的2种事务隔离级别:READ COMMITTED,SERIALIZABLE。Oracle默认的事务隔离级别为READ COMMITTED
  • MySQL支持4种事务隔离级别,MySQL默认的事务隔离级别为REPEATABLE READ

在MySQL中设置隔离级别

  • 每启动一个MySQL程序,就会获得一个单独的数据库连接,每个数据库连接都有一个全局变量@@tx_isolation,表示当前的事务隔离级别
  • 查看当前的隔离级别:select @@tx_isolation;
  • 设置当前MySQL连接的隔离级别:set transaction isolation level read committed;
  • 设置数据库系统的全局的隔离级别:set global transaction isolation level read committed;

视图的讲解

视图:MySQL从5.0.1版本开始提供视图功能。一种虚拟存在的表,行和列的数据来自定义视图的查询中使用的表,并且是在使用视图时动态生成的。

视图的好处:

  1. 重用sql语句
  2. 简化复杂的sql操作,不必知道它的查询细节
  3. 保护数据,提高安全性

一、创建视图

语法

1
2
3
create view 视图名
as
查询语句;

案例

1
2
3
4
5
6
7
8
9
10
#1.查询姓名中包含a字符的员工名、部门名和工种信息
#①创建
create view myv1
as
select last_name,department_name,job_title
from employees e
join departments d on e.department_id=d.department_id
join jobs j on j.job_id=e.job_id;
#②使用
select * from myv1 where last_name like '&a&';

二、修改视图

语法

1
2
3
4
5
6
7
8
9
#方式一
create or replace view 视图名
as
查询语句;

#方式二
alter view 视图名
as
查询语句;

三、删除视图

语法

1
drop view 视图名,视图名,...;

四、查看视图

语法

1
2
3
desc 视图名;
#或
show create view 视图名;

五、更新视图

视图一般用于查询的,而不是更新的,视图的可更新性和视图中查询的定义有关系,以下类型的视图是不能更新的

  • 包含以下关键子的sql语句:分组函数、distinct、group by、having、union或者union all
  • 常量视图
  • select中包含子查询
  • join
  • from一个不能更新的视图
  • where 子句的子查询引用了from子句中的表
1
2
3
4
5
6
7
8
#1.插入
insert into myv1 values('张飞','zf@qq.com');

#2.修改
update myv1 set last_name='张无忌'where last_name='张飞';

#3.删除
delete from myv1 where last_name='张无忌';

变量

一、系统变量

说明:变量由系统提供的,不是用户定义,属于服务器层面

全局变量

作用域:服务器每次启动将为所有的全局变量赋初始值

1
2
3
4
5
6
7
8
9
10
11
#1、查看所有的全局变量
show global variables;

#2、查看满足条件的部分全局变量
show global variables like '%char%';

#3、查看某个指定的全局变量的值
select @@global.全局变量名;
select @@全局变量名;
#4、为某个全局变量赋值
set @@global.全局变量名=值;

会话变量

作用域:仅仅针对当前会话(连续)有效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#1、查看所有的会话变量
show session variables;

#2、查看满足条件的部分会话变量
show session variables like '%char%';

#3、查看某个指定的会话变量的值
select @@会话变量名;
select @@session .会话变量名;

#4、为某个会话变量赋值
#方式一
set session 会话变量名=值;
#方式二
set @@session.会话变量名=值;

注意:如果不写global或,默认session

自定义变量

说明:变量是用户自定义的,不是由系统的

使用步骤:

声明

赋值

使用(查看、比较、运算等)

用户变量

作用域:针对于当前会话(连接)有效,同于会话变量的作用域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#①声明并初始化
set @用户变量名=值;
set @用户变量名:=值;
select@用户变量名:=值;

#②赋值(更新用户变量的值)
#方式一:通过setselect
set @用户变量名=值;
set @用户变量名:=值;
select@用户变量名:=值;
#方式二:通过select into
select 字段 into 变量名
from 表;

#③使用(查看某个用户变量的值)
select @用户变量名;

局部变量

作用域:仅仅在定义它的begin end 中有效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#①声明
declare 变量名 类型;
declare 变量名 类型 default 值;

#②赋值
#方式一:通过setselect
set 局部变量名=值;
set 局部变量名:=值;
select@局部变量名:=值;
#方式二:通过select into
select 字段 into 局部变量名
from 表;

#③使用
select 局部变量名;

存储过程和函数

存储过程

存储过程含义:一组预先编译好的sql语句的集合,理解成批处理语句

好处:

  1. 提高代码的重用性,
  2. 简化操作,
  3. 减少了编译次数,并且减少了和数据库服务器的连接次数,提高了效率

一、创建语法

1
2
3
4
create procedure 存储过程名(参数列表)
begin
存储过程体(一组合法的sql语句)
end

注意事项:

  1. 参数列表包含三部分

    参数模式 参数名 参数类型 举例:in stuname varchar(20)

    参数模式:

    in:该参数可以作为输入,也就是该参数需要调用方传入值

    out:该参数可以作为输出,也就是该参数可以作为返回值

    inout:该参数既可以作为输入又可以作为输出,也就是该参数既需要传入值,又可以返回值

  2. 如果存储过程体仅仅只有一句话,begin和end可以省略

  3. 存储过程中的每条sql语句的结尾要求必须加分号

    存储过程结尾可以使用delimiter重新设置 delimiter 结束标记

二、调用语法

1
call 存储过程名(实参列表);

三、删除存储过程

1
drop procedure 存储过程名;

四、查看存储过程

1
show create procedure 存储过程名;

函数

含义:一组预先编译好的sql语句的集合,理解成批处理语句

好处:

  1. 提高代码的重用性,
  2. 简化操作,
  3. 减少了编译次数,并且减少了和数据库服务器的连接次数,提高了效率

和存储过程的区别:

存储过程:可以有0个返回,也可以有多个返回,适合做批量插入,批量更新

函数:有且仅有一个返回,适合做处理数据后返回一个结果

一、创建语法

1
2
3
4
create function 函数名(参数列表) returns 返回类型
begin
函数体
end

注意:

  1. 参数列表包含两部分:参数名 参数类型

  2. 函数体:肯定会有reture语句,如果没有会报错

    ​ 如果return语句没有放在函数体的最后也不报错,但不建议

  3. 函数体中仅有一句话,则可以省略begin end

  4. 使用delimiter语句设置结束标记

二、调用语法

1
select 函数名(参数列表)

三、查看函数

1
show create function 函数名;

四、删除函数

1
drop function 函数名;

流程控制结构

顺序结构:程序从上往下依次执行

分支结构:程序从两条或多条路径中选择一条去执行

循环结构:程序在满足一定条件的基础上,重复执行一段代码

一、分支结构

  1. if函数

    功能:实现简单的双分支

    语法:if(表达式1,表达式2,表达式3)

    执行顺序:如果表达式1成立,则返回表达式2的值,否则返回表达式3的值

    应用:任何地方

  2. case结构

    • 情况1:类似Java中的switch语句,一般用于实现等值判断

      语法:case 变量|表达式|字段

      ​ when 要判断的值 then 返回的值1或语句1;

      ​ when 要判断的值 then 返回的值2或语句2;

      ​ …

      ​ else 要返回的值n或语句n;

      ​ end case;

    • 情况2:类似Java中的多重if语句,一般用于实现区间判断

      语法:case

      ​ when 要判断的条件1 then 返回的值1或语句1;

      ​ when 要判断的条件2 then 返回的值2或语句2;

      ​ …

      ​ else 要返回的值n或语句n;

      ​ end case;

    特点:

    1. 可以作为表达式,嵌套在其他语句中使用,可以放在任何地方,begin end中,或begin end的外面

      可以作为独立的语句去使用,只能放在begin end中

    2. 如果when中的值满足或条件成立,则执行对应的then后面的语句,并且结束case

      如果都不满足,则执行else中的语句或值

    3. else可以省略,如果else省略了,并且所有when条件都不满足,则返回null

  3. if结构

    功能:实现多重分支

    语法:

    ​ if 条件1 then 语句1;

    ​ elseif 条件2 then 语句2;

    ​ …

    ​ [else 语句n]

    ​ end if

二、循环结构

分类:while 、loop、repeat

循环控制:

inerate 类似于 continue,继续,结束本次循环,继续下一次

leave 类似于 break ,跳出,结束当前所在循环

  1. while

    语法:

    ​ while 循环条件 do

    ​ 循环体;

    ​ end while;

    特点:先判断后执行

  2. loop

    语法:

    ​ loop

    ​ 循环体;

    ​ end loop;

    特点:可以用来模拟简单的死循环

  3. repeat

    语法:

    ​ repeat

    ​ 循环体;

    ​ until 结束循环的条件

    ​ end repeat;

    特点:先执行后判断