第1章 MySQL安装
1.1 windows版下载地址
1.2 添加环境变量
1.3 初始化
1.4 启动mysql服务
1.5 链接mysql
1.6 制作mysql的windows服务
1.7 启停MySQL服务
第2章 mysql基本命令
2.1 mysql命令
2.2 windows-cmd命令
2.3 统一字符编码
第3章 数据类型
3.1 数字:
3.2 小数:
3.3 字符串:
3.4 时间类型:
3.5 枚举类型与集合类型
3.6 数值类型
3.6.1 例:验证符号有无
3.6.2 无符号tinyint
3.6.3 数值类型统计表
3.7 字符类型
3.7.1 char
3.7.2 varchar
3.7.3 小结
3.8 枚举、集合类型
3.8.1 使用方法
3.8.2 举例说明
第4章 完整性约束
4.1 介绍
4.2 参数介绍
4.3 not null 与default
4.4 defaut
4.5 unique
4.5.1 联合唯一
4.6 primary key
4.6.1 单列主键
4.6.2 复合主键
4.7 auto_increment
4.7.1 指定id存储
4.7.2 truncate
4.8 foreign key
4.9 关联表同步删除
4.9.1 操作流程
第5章 外键变种三种关系
5.1 多对一
5.2 多对多
5.3 一对一
第6章 数据增删改
第7章 单表查询
7.1 查询语法
7.2 关键字优先级
7.3 实战
7.4 where
7.4.1 单条件查询
7.4.2 多条件查询
7.4.3 关键字BETWEEN AND
7.4.4 关键字IN集合查询
7.4.5 关键字LIKE模糊查询
7.4.6 练习:
7.5 group by 分组查询
7.5.1 使用说明
7.5.2 参数设置
7.6 聚合函数
7.6.1 实战练习
7.7 having
7.7.1 用法
7.7.2 having/where的区别
7.7.3 实战练习
7.8 order by 查询排序
7.8.1 用法
7.8.2 实战练习
7.9 limit
7.9.1 用法:
7.9.2 实战练习
第8章 多表查询
8.1 多表链接查询
8.1.1 要求:
8.1.2 重点:外链接语法
8.2 符合条件链接查询
8.3 子查询
8.3.1 作用
8.3.2 实战练习
8.3.3 练习:查询每个部门最新入职的那位员工
第9章 localstore
9.1 永久存储
9.2 会话存储
第10章 pymysql
10.1 介绍
10.2 本地安装方法
10.2.1 装模块
10.2.2 mysql创建库
10.2.3 创建表
10.2.4 插入数据
10.3 pymysql模块使用
10.4 execute()之sql注入
10.4.1 两种注入方式
10.4.2 execute()解决方法
10.5 插入
10.6 改
10.7 删
10.8 插入删除更新要commit
10.9 查询
10.9.1 fetchone()
10.9.2 fetchall()
10.9.3 fetchmany():
10.10 查询结果转换
10.11 指针控制
10.12 实战练习
第11章 索引
第1章 MySQL安装
1.1 windows版下载地址
官网下载:https://dev.mysql.com/downloads/mysql/
1.2 添加环境变量
【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【将MySQL的bin目录路径追加到变值值中,用 ; 分割】
1.3 初始化
mysqld --initialize-insecure
1.4 启动mysql服务
mysqld #启动MySQL服务
1.5 链接mysql
启动mysql客户端并连接mysql服务端(新开一个cmd窗口)
mysql -u root -p # 连接MySQL服务器
1.6 制作mysql的windows服务
上一步解决了一些问题,但不够彻底,因为在执行【mysqd】启动MySQL服务器时,当前终端会被hang住,那么做一下设置即可解决此问题,即将MySQL服务制作成windows服务
注意:--install前,必须用mysql启动命令的绝对路径
# 制作MySQL的Windows服务,在终端执行此命令:
"c:\mysql-5.6.40-winx64\bin\mysqld" --install
# 移除MySQL的Windows服务,在终端执行此命令:
"c:\mysql-5.7.16-winx64\bin\mysqld" --remove
注册成服务之后,以后再启动和关闭MySQL服务时,仅需执行如下命令:
1.7 启停MySQL服务
net start mysql
# 关闭MySQL服务
net stop mysql
第2章 mysql基本命令
2.1 mysql命令
mysqladmin -uroot -p password "123" #设置初始密码 由于原密码为空
select user(); # 查看当前登录的账号
mysqladmin -uroot -p"123" password "456" #修改mysql密码,因为已经有密码了,所以必须输入原密码才能设置新密码
\s
create database db1 charset utf8;
# 查看当前创建的数据库
show create database db1;
# 查看所有的数据库
show databases;
alter database db1 charset gbk;
drop database db1;
use db1;
create table t1(id int,name char);
#查看当前的这张t1表
show create table t1;
# 查看所有的表
show tables;
# 查看表的详细信息
desc t1
# modify修改的意思
alter table t1 modify name char(6);
# 改变name为大写的NAME
alter table t1 change name NAMA char(7);
# 删除表
drop table t1;
# 插入一条数据,规定id,name数据leilei
insert t1(id,name) values(1,"mjj01"),(2,"mjj02"),(3,"mjj03");
查
select id from db1.t1;
select id,name from db1.t1;
select * from db1.t1;
改
update db1.t1 set name='zhangsan';
update db1.t1 set name='alex' where id=2;
删
delete from t1;
delete from t1 where id=2;
#查看数据库
show databases;
#查看当前库
show create database db1;
#查看所在的库
select database();
#选择数据库
use 数据库名
#删除数据库
DROP DATABASE 数据库名;
# 修改数据库
alter database db1 charset utf8;
mysql> show engines\G;# 查看所有支持的引擎
mysql> show variables like 'storage_engine%'; # 查看正在使用的存储引擎
#建表
create table a1(
id int,
name varchar(50),
age int(3)
);
#查寻表
select * from a1;
#查寻表结构
desc a1;
show create table a1\G;
#查看库中的表
select * from db2.a1;
#复制db2.a1中的表结构和记录
create table b1 select * from db2.a1;
#只要表结构不要记录
create table b2 select * from db2.a1 where 1>5;
create table b3 like db2.a1;
重置密码
net stop mysql
mysqld --skip-grant-tables
update mysql.user set authentication_string =password('') where User='root';
flush privileges;
2.2 windows-cmd命令
tasklist |findstr mysql #查看当前mysql的进程
taskkill /F /PID 6052 # 杀死当前的进程pid
2.3 统一字符编码
(1)my.ini文件是mysql的配置文件,
在C:\mysql-5.6.40-winx64文件下创建my.ini文件
(2)将如下代码拷贝保存。
#mysql5.5以上:修改方式为
[mysqld]
# 设置mysql的安装目录
basedir=C:\mysql-5.7.22-winx64\mysql-5.7.22-winx64
# 设置mysql数据库的数据的存放目录,必须是data
datadir=C:\mysql-5.7.22-winx64\mysql-5.7.22-winx64\data
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
# mysql端口
port=3306
# 字符集
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
[client]
default-character-set=utf8
[mysql]
default-character-set=utf8
第3章 数据类型
详细参考链接:http://www.runoob.com/mysql/mysql-data-types.html
https://www.cnblogs.com/majj/p/9164480.html
3.1 数字:
整型:tinyint int bigint
3.2 小数:
float :在位数比较短的情况下不精准
double :在位数比较长的情况下不精准
0.000001230123123123
存成:0.000001230000
decimal:(如果用小数,则用推荐使用decimal)
精准
内部原理是以字符串形式去存
3.3 字符串:
char(10):简单粗暴,浪费空间,存取速度快
root存成root000000
varchar:精准,节省空间,存取速度慢
sql优化:创建表时,定长的类型往前放,变长的往后放
比如性别 比如地址或描述信息
>255个字符,超了就把文件路径存放到数据库中。
比如图片,视频等找一个文件服务器,数据库中只存路径或url。
3.4 时间类型:
最常用:datetime
3.5 枚举类型与集合类型
enum 和set
3.6 数值类型
整数类型:TINYINT SMALLINT MEDIUMINT INT BIGINT
作用:存储年龄,等级,id,各种号码等
========================================
tinyint[(m)] [unsigned] [zerofill]
小整数,数据类型用于保存一些范围的整数数值范围:
有符号:
-128 ~ 127
无符号:
~ 255
PS: MySQL中无布尔值,使用tinyint(1)构造。
========================================
int[(m)][unsigned][zerofill]
整数,数据类型用于保存一些范围的整数数值范围:
有符号:
-2147483648 ~ 2147483647
无符号:
~ 4294967295
========================================
bigint[(m)][unsigned][zerofill]
大整数,数据类型用于保存一些范围的整数数值范围:
有符号:
-9223372036854775808 ~ 9223372036854775807
无符号:
~ 18446744073709551615
3.6.1 例:验证符号有无
============有符号tinyint==============
# 创建数据库db4
create database db4 charset utf8;
# 切换到当前db4数据库
mysql> use db4;
# 创建t1 规定x字段为tinyint数据类型(默认是有符号的)
mysql> create table t1(x tinyint);
# 验证,插入-1这个数
mysql> insert into t1 values(-1);
# 查询 表记录,查询成功(证明默认是有符号类型)
mysql> select * from t1;
+------+
| x |
+------+
| -1 |
+------+
#执行如下操作,会发现报错。因为有符号范围在(-128,127)
mysql> insert into t1 values(-129),(128);
ERROR 1264 (22003): Out of range value for column 'x' at row 1
3.6.2 无符号tinyint
# 创建表时定义记录的字符为无符号类型(0,255) ,使用unsigned
mysql> create table t2(x tinyint unsigned);
# 报错,超出范围
mysql> insert into t2 values(-129);
ERROR 1264 (22003): Out of range value for column 'x' at row 1
# 插入成功
mysql> insert into t2 values(255);
Query OK, 1 row affected (0.00 sec)
验证2:int类型后面的存储是显示宽度,而不是存储宽度
mysql> create table t3(id int(1) unsigned);
#插入255555记录也是可以的
mysql> insert into t3 values(255555);
mysql> select * from t3;
+--------+
| id |
+--------+
| 255555 |
+--------+
ps:以上操作还不能够验证,再来一张表验证用zerofill 用0填充
# zerofill 用0填充
mysql> create table t4(id int(5) unsigned zerofill);
mysql> insert into t4 value(1);
Query OK, 1 row affected (0.00 sec)
#插入的记录是1,但是显示的宽度是00001
mysql> select * from t4;
+-------+
| id |
+-------+
| 00001 |
+-------+
row in set (0.00 sec)
3.6.3 数值类型统计表
3.7 字符类型
3.7.1 char
l 定义:char类型:定长,简单粗暴,浪费空间,存取速度快
l 字符长度范围:0-255(一个中文是一个字符,是utf8编码的3个字节)
l 存储:
存储char类型的值时,会往右填充空格来满足长度
例如:指定长度为10,存>10个字符则报错,存<10个字符则用空格填充直到凑够10个字符存储
l 检索:
在检索或者说查询时,查出的结果会自动删除尾部的空格,除非我们打开pad_char_to_full_length SQL模式(设置SQL模式:SET sql_mode = 'PAD_CHAR_TO_FULL_LENGTH'; 查询sql的默认模式:select @@sql_mode;)
3.7.2 varchar
#varchar类型:变长,精准,节省空间,存取速度慢
l 字符长度范围:
0-65535(如果大于21845会提示用其他类型 。mysql行最大限制为65535字节,字符编码为utf-8:https://dev.mysql.com/doc/refman/5.7/en/column-count-limit.html)
l 存储:
varchar类型存储数据的真实内容,不会用空格填充,如果'ab ',尾部的空格也会被存起来
强调:varchar类型会在真实数据前加1-2Bytes的前缀,该前缀用来表示真实数据的bytes字节数(1-2Bytes最大表示65535个数字,正好符合mysql对row的最大字节限制,即已经足够使用)
如果真实的数据<255bytes则需要1Bytes的前缀(1Bytes=8bit 2**8最大表示的数字为255)
如果真实的数据>255bytes则需要2Bytes的前缀(2Bytes=16bit 2**16最大表示的数字为65535)
l 检索:
尾部有空格会保存下来,在检索或者说查询时,也会正常显示包含空格在内的内容
3.7.3 小结
常用字符串系列:char与varchar
注:虽然varchar使用起来较为灵活,但是从整个系统的性能角度来说,char数据类型的处理速度更快,有时甚至可以超出varchar处理速度的50%。因此,用户在设计数据库时应当综合考虑各方面的因素,以求达到最佳的平衡
#其他字符串系列(效率:char>varchar>text)
TEXT系列 TINYTEXT TEXT MEDIUMTEXT LONGTEXT
BLOB 系列 TINYBLOB BLOB MEDIUMBLOB LONGBLOB
BINARY系列 BINARY VARBINARY
text:text数据类型用于保存变长的大字符串,可以组多到65535 (2**16 − 1)个字符。
mediumtext:A TEXT column with a maximum length of 16,777,215 (2**24 − 1) characters.
longtext:A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32 − 1) characters.
3.8 枚举、集合类型
3.8.1 使用方法
字段的值只能在给定范围中选择,如单选框,多选框
enum 单选 只能在给定的范围内选一个值,如性别 sex 男male/女female
set 多选 在给定的范围内可以选择一个或一个以上的值(爱好1,爱好2,爱好3...)
3.8.2 举例说明
mysql> create table consumer(
-> id int,
-> name varchar(50),
-> sex enum('male','female','other'),
-> level enum('vip1','vip2','vip3','vip4'),#在指定范围内,多选一
-> fav set('play','music','read','study') #在指定范围内,多选多
-> );
Query OK, 0 rows affected (0.03 sec)
mysql> insert into consumer values
-> (1,'赵云','male','vip2','read,study'),
-> (2,'赵云2','other','vip4','play');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from consumer;
+------+---------+-------+-------+------------+
| id | name | sex | level | fav |
+------+---------+-------+-------+------------+
| 1 | 赵云 | male | vip2 | read,study |
| 2 | 赵云2 | other | vip4 | play |
+------+---------+-------+-------+------------+
2 rows in set (0.00 sec)
第4章 完整性约束
4.1 介绍
约束条件与数据类型的宽度一样,都是可选参数
作用:用于保证数据的完成性和一致性
4.2 参数介绍
PRIMARY KEY (PK) #标识该字段为该表的主键,可以唯一的标识记录
FOREIGN KEY (FK) #标识该字段为该表的外键
NOT NULL #标识该字段不能为空
UNIQUE KEY (UK) #标识该字段的值是唯一的
AUTO_INCREMENT #标识该字段的值自动增长(整数类型,而且为主键)
DEFAULT #为该字段设置默认值
UNSIGNED #无符号
ZEROFILL #使用0填充
4.3 not null 与default
not null :不可空
null: 可空
创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
create table tb2(
nid int not null defalut 2,
num int not null
);
例:
mysql> create table t12(id int not null);#设置字段id不为空
Query OK, 0 rows affected (0.03 sec)
mysql> desc t12;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | NO | | NULL | |
+-------+---------+------+-----+---------+-------+
row in set (0.01 sec)
mysql> insert into t12 values();#不能插入空
ERROR 1364 (HY000): Field 'id' doesn't have a default value
设置not null,插入值时不能为空
4.4 defaut
解释:设置id字段有默认值后,则无论id字段是null还是not null,都可以插入空,插入空默认填入default指定的默认值
# 第一种情况
mysql> create table t13(id int default 1);
Query OK, 0 rows affected (0.03 sec)
mysql> desc t13;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | YES | | 1 | |
+-------+---------+------+-----+---------+-------+
row in set (0.01 sec)
mysql> insert into t13 values();
Query OK, 1 row affected (0.00 sec)
mysql> select * from t13;
+------+
| id |
+------+
| 1 |
+------+
row in set (0.00 sec)
# 第二种情况
mysql> create table t14(id int not null default 2);
Query OK, 0 rows affected (0.02 sec)
mysql> desc t14;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id | int(11) | NO | | 2 | |
+-------+---------+------+-----+---------+-------+
row in set (0.01 sec)
mysql> select * from t14;
+----+
| id |
+----+
| 2 |
+----+
row in set (0.00 sec)
练习:
mysql> create table student2(
-> id int not null,
-> name varchar(50) not null,
-> age int(3) unsigned not null default 18,
-> sex enum('male','female') default 'male',
-> fav set('smoke','drink','tangtou') default 'drink,tangtou'
-> );
# 查询结果如下
mysql> select * from student2;
+----+------+-----+------+---------------+
| id | name | age | sex | fav |
+----+------+-----+------+---------------+
| 1 | mjj | 18 | male | drink,tangtou |
+----+------+-----+------+---------------+
1 row in set (0.00 sec)
4.5 unique
作用:单列唯一
例:
同时插入两个IT部门也是可以的,但这是不合理的,所以我们要设置name字段为unique 解决这种不合理的现象。
#第一种创建unique的方式
#例子1:
create table department(
id int,
name char(10) unique
);
mysql> insert into department values(1,'it'),(2,'it');
ERROR 1062 (23000): Duplicate entry 'it' for key 'name'
#例子2:
create table department(
id int unique,
name char(10) unique
);
insert into department values(1,'it'),(2,'sale');
#第二种创建unique的方式
create table department(
id int,
name char(10) ,
unique(id),
unique(name)
);
insert into department values(1,'it'),(2,'sale');
第二种创建方式
#第二种创建unique的方式
create table department(
id int,
name char(10) ,
unique(id),
unique(name)
);
insert into department values(1,'it'),(2,'sale');
4.5.1 联合唯一
#联合唯一,只要两列记录,有一列不同,既符合联合唯一的约束
mysql> create table services(
-> id int,
-> ip char(15),
-> port int,
-> unique(id),
-> unique(ip,port)
-> );
Query OK, 0 rows affected (0.05 sec)
mysql> desc services;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | YES | UNI | NULL | |
| ip | char(15) | YES | MUL | NULL | |
| port | int(11) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.01 sec)
mysql> insert into services values (4,'192,168,11,23',80);
ERROR 1062 (23000): Duplicate entry '192,168,11,23-80' for key 'ip'
4.6 primary key
主键分为:
单列主键
多列主键(复合主键)
约束:等价于not null unipue,字段的值不为空且唯一
存储引擎默认是(innodb):对于innodb存储引擎来说,一张表必须有主键
4.6.1 单列主键
# 创建t14表,为id字段设置主键,唯一的不同的记录
create table t14(
id int primary key,
name char(16)
);
insert into t14 values
(1,'xiaoma'),
(2,'xiaohong');
mysql> insert into t14 values(2,'wxxx');
ERROR 1062 (23000): Duplicate entry '6' for key 'PRIMARY'
# not null + unique的化学反应,相当于给id设置primary key
create table t15(
id int not null unique,
name char(16)
);
mysql> create table t15(
-> id int not null unique,
-> name char(16)
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> desc t15;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | char(16) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.02 sec)
4.6.2 复合主键
create table t16(
ip char(15),
port int,
primary key(ip,port)
);
insert into t16 values
('1.1.1.2',80),
('1.1.1.2',81);
验证复合主键的使用
4.7 auto_increment
作用:约束的字段为自动增长,约束的字段必须同时被key约束
验证:
不指定id,则自动增长
# 创建student
create table student(
id int primary key auto_increment,
name varchar(20),
sex enum('male','female') default 'male'
);
mysql> desc student;
+-------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| sex | enum('male','female') | YES | | male | |
+-------+-----------------------+------+-----+---------+----------------+
3 rows in set (0.17 sec)
插入记录
mysql> insert into student(name) values ('老白'),('小白');
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from student;
+----+--------+------+
| id | name | sex |
+----+--------+------+
| 1 | 老白 | male |
| 2 | 小白 | male |
+----+--------+------+
2 rows in set (0.00 sec)
4.7.1 指定id存储
mysql> insert into student values(7,'wsb','female');
Query OK, 1 row affected (0.01 sec)
mysql> select * from student;
+----+--------+--------+
| id | name | sex |
+----+--------+--------+
| 1 | 老白 | male |
| 2 | 小白 | male |
| 4 | asb | female |
| 7 | wsb | female |
+----+--------+--------+
4 rows in set (0.00 sec
再次插入一条不指定id的记录,会在之前的最后一条记录继续增长
mysql> insert into student(name) values ('大白');
Query OK, 1 row affected (0.00 sec)
mysql> select * from student;
+----+--------+--------+
| id | name | sex |
+----+--------+--------+
| 1 | 老白 | male |
| 2 | 小白 | male |
| 4 | asb | female |
| 7 | wsb | female |
| 8 | 大白 | male |
+----+--------+--------+
5 rows in set (0.00 sec)
对于自增的字段,在用delete删除后,再插入值,该字段仍按照删除前的位置继续增长
mysql> insert into student(name) values('ysb');
Query OK, 1 row affected (0.01 sec)
mysql> select * from student;
+----+------+------+
| id | name | sex |
+----+------+------+
| 9 | ysb | male |
+----+------+------+
row in set (0.00 sec)
4.7.2 truncate
清空表,id归零
delete from t1; #如果有自增id,新增的数据,仍然是以删除前的最后一样作为起始。
truncate table t1;数据量大,删除速度比上一条快,且直接从零开始。
mysql> truncate student;
Query OK, 0 rows affected (0.03 sec)
mysql> insert into student(name) values('xiaobai');
Query OK, 1 row affected (0.00 sec)
mysql> select * from student;
+----+---------+------+
| id | name | sex |
+----+---------+------+
| 1 | xiaobai | male |
+----+---------+------+
row in set (0.00 sec)
4.8 foreign key
此时有两张表,一张是employee表,简称emp表(关联表,也就从表)。一张是department表,简称dep表(被关联表,也叫主表)
主表
mysql> select * from dep;
+----+-----------+----------------------+
| id | name | descripe |
+----+-----------+----------------------+
| 1 | IT | IT技术有限部门 |
| 2 | 销售部 | 销售部门 |
| 3 | 财务部 | 花钱太多部门 |
+----+-----------+----------------------+
3 rows in set (0.01 sec)
从表:以从表的哥是将两个表进行组合
mysql> select * from emp;
+----+----------+-----+--------+
| id | name | age | dep_id |
+----+----------+-----+--------+
| 1 | zhangsan | 18 | 1 |
| 2 | lisi | 19 | 1 |
| 3 | egon | 20 | 2 |
| 4 | yuanhao | 40 | 3 |
| 5 | alex | 18 | 2 |
+----+----------+-----+--------+
5 rows in set (0.00 sec)
操作方法:
#1.创建表时先创建被关联表,再创建关联表
# 先创建被关联表(dep表)
create table dep(
id int primary key,
name varchar(20) not null,
descripe varchar(20) not null
);
#再创建关联表(emp表)
create table emp(
id int primary key,
name varchar(20) not null,
age int not null,
dep_id int,
constraint fk_dep foreign key(dep_id) references dep(id)
);
#2.插入记录时,先往被关联表中插入记录,再往关联表中插入记录
insert into dep values
(1,'IT','IT技术有限部门'),
(2,'销售部','销售部门'),
(3,'财务部','花钱太多部门');
insert into emp values
(1,'zhangsan',18,1),
(2,'lisi',19,1),
(3,'egon',20,2),
(4,'yuanhao',40,3),
(5,'alex',18,2);
3.删除表
#按道理来说,删除了部门表中的某个部门,员工表的有关联的记录相继删除。
mysql> delete from dep where id=3;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`db5`.`emp`, CONSTRAINT `fk_name` FOREIGN KEY (`dep_id`) REFERENCES `dep` (`id`))
#但是先删除员工表的记录之后,再删除当前部门就没有任何问题
mysql> delete from emp where dep =3;
Query OK, 1 row affected (0.00 sec)
mysql> select * from emp;
+----+----------+-----+--------+
| id | name | age | dep_id |
+----+----------+-----+--------+
| 1 | zhangsan | 18 | 1 |
| 2 | lisi | 18 | 1 |
| 3 | egon | 20 | 2 |
| 5 | alex | 18 | 2 |
+----+----------+-----+--------+
4 rows in set (0.00 sec)
mysql> delete from dep where id=3;
Query OK, 1 row affected (0.00 sec)
mysql> select * from dep;
+----+-----------+----------------------+
| id | name | descripe |
+----+-----------+----------------------+
| 1 | IT | IT技术有限部门 |
| 2 | 销售部 | 销售部门 |
+----+-----------+----------------------+
2 rows in set (0.00 sec)
4.9 关联表同步删除
l on delete cascade #同步删除
l on update cascade #同步更新
4.9.1 操作流程
create table emp(
id int primary key,
name varchar(20) not null,
age int not null,
dep_id int,
constraint fk_dep foreign key(dep_id) references dep(id)
on delete cascade #同步删除
on update cascade #同步更新
);
#再去删被关联表(dep)的记录,关联表(emp)中的记录也跟着删除
mysql> delete from dep where id=3;
Query OK, 1 row affected (0.00 sec)
mysql> select * from dep;
+----+-----------+----------------------+
| id | name | descripe |
+----+-----------+----------------------+
| 1 | IT | IT技术有限部门 |
| 2 | 销售部 | 销售部门 |
+----+-----------+----------------------+
2 rows in set (0.00 sec)
mysql> select * from emp;
+----+----------+-----+--------+
| id | name | age | dep_id |
+----+----------+-----+--------+
| 1 | zhangsan | 18 | 1 |
| 2 | lisi | 19 | 1 |
| 3 | egon | 20 | 2 |
| 5 | alex | 18 | 2 |
+----+----------+-----+--------+
4 rows in set (0.00 sec)
再去更改被关联表(dep)的记录,关联表(emp)中的记录也跟着更改
mysql> update dep set id=222 where id=2;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
# 赶紧去查看一下两张表是否都被删除了,是否都被更改了
mysql> select * from dep;
+-----+-----------+----------------------+
| id | name | descripe |
+-----+-----------+----------------------+
| 1 | IT | IT技术有限部门 |
| 222 | 销售部 | 销售部门 |
+-----+-----------+----------------------+
2 rows in set (0.00 sec)
mysql> select * from emp;
+----+----------+-----+--------+
| id | name | age | dep_id |
+----+----------+-----+--------+
| 1 | zhangsan | 18 | 1 |
| 2 | lisi | 19 | 1 |
| 3 | egon | 20 | 222 |
| 5 | alex | 18 | 222 |
+----+----------+-----+--------+
4 rows in set (0.00 sec)
第5章 外键变种三种关系
5.1 多对一
一对多(或多对一):一个出版社可以出版多本书。看图说话。
关联方式:foreign key
create table press(
id int primary key auto_increment,
name varchar(20)
);
create table book(
id int primary key auto_increment,
name varchar(20),
press_id int not null,
constraint fk_book_press foreign key(press_id) references press(id)
on delete cascade
on update cascade
);
# 先往被关联表中插入记录
insert into press(name) values
('北京工业地雷出版社'),
('人民音乐不好听出版社'),
('知识产权没有用出版社')
;
# 再往关联表中插入记录
insert into book(name,press_id) values
('九阳神功',1),
('九阴真经',2),
('九阴白骨爪',2),
('独孤九剑',3),
('降龙十巴掌',2),
('葵花宝典',3)
;
查询结果:
mysql> select * from book;
+----+-----------------+----------+
| id | name | press_id |
+----+-----------------+----------+
| 1 | 九阳神功 | 1 |
| 2 | 九阴真经 | 2 |
| 3 | 九阴白骨爪 | 2 |
| 4 | 独孤九剑 | 3 |
| 5 | 降龙十巴掌 | 2 |
| 6 | 葵花宝典 | 3 |
+----+-----------------+----------+
rows in set (0.00 sec)
mysql> select * from press;
+----+--------------------------------+
| id | name |
+----+--------------------------------+
| 1 | 北京工业地雷出版社 |
| 2 | 人民音乐不好听出版社 |
| 3 | 知识产权没有用出版社 |
+----+--------------------------------+
rows in set (0.00 sec)
书和出版社(多对一)
5.2 多对多
作者与书的关系
# 创建被关联表author表,之前的book表在讲多对一的关系已创建
create table author(
id int primary key auto_increment,
name varchar(20)
);
#这张表就存放了author表和book表的关系,即查询二者的关系查这表就可以了
create table author2book(
id int not null unique auto_increment,
author_id int not null,
book_id int not null,
constraint fk_author foreign key(author_id) references author(id)
on delete cascade
on update cascade,
constraint fk_book foreign key(book_id) references book(id)
on delete cascade
on update cascade,
primary key(author_id,book_id)
);
#插入四个作者,id依次排开
insert into author(name) values('egon'),('alex'),('wusir'),('yuanhao');
# 每个作者的代表作
egon: 九阳神功、九阴真经、九阴白骨爪、独孤九剑、降龙十巴掌、葵花宝典
alex: 九阳神功、葵花宝典
wusir:独孤九剑、降龙十巴掌、葵花宝典
yuanhao:九阳神功
# 在author2book表中插入相应的数据
insert into author2book(author_id,book_id) values
(1,1),
(1,2),
(1,3),
(1,4),
(1,5),
(1,6),
(2,1),
(2,6),
(3,4),
(3,5),
(3,6),
(4,1)
;
# 现在就可以查author2book对应的作者和书的关系了
mysql> select * from author2book;
+----+-----------+---------+
| id | author_id | book_id |
+----+-----------+---------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 1 | 4 |
| 5 | 1 | 5 |
| 6 | 1 | 6 |
| 7 | 2 | 1 |
| 8 | 2 | 6 |
| 9 | 3 | 4 |
| 10 | 3 | 5 |
| 11 | 3 | 6 |
| 12 | 4 | 1 |
+----+-----------+---------+
rows in set (0.00 sec)
作者与书籍关系(多对多)
5.3 一对一
一个用户只能注册一个博客
一个用户只能注册一个博客
#例如: 一个用户只能注册一个博客
#两张表: 用户表 (user)和 博客表(blog)
# 创建用户表
create table user(
id int primary key auto_increment,
name varchar(20)
);
# 创建博客表
create table blog(
id int primary key auto_increment,
url varchar(100),
user_id int unique,
constraint fk_user foreign key(user_id) references user(id)
on delete cascade
on update cascade
);
#插入用户表中的记录
insert into user(name) values
('alex'),
('wusir'),
('egon'),
('xiaoma')
;
# 插入博客表的记录
insert into blog(url,user_id) values
('http://www.cnblog/alex',1),
('http://www.cnblog/wusir',2),
('http://www.cnblog/egon',3),
('http://www.cnblog/xiaoma',4)
;
# 查询wusir的博客地址
select url from blog where user_id=2;
第6章 数据增删改
一、
在MySQL管理软件中,可以通过SQL语句中的DML语言来实现数据的操作,包括
l 使用INSERT实现数据的插入
l UPDATE实现数据的更新
l 使用DELETE实现数据的删除
l 使用SELECT查询数据以及。
二、插入数据 INSERT
1. 插入完整数据(顺序插入)
语法一:
INSERT INTO 表名(字段1,字段2,字段3…字段n) VALUES(值1,值2,值3…值n);
语法二:
INSERT INTO 表名 VALUES (值1,值2,值3…值n);
2. 指定字段插入数据
语法:
INSERT INTO 表名(字段1,字段2,字段3…) VALUES (值1,值2,值3…);
3. 插入多条记录
语法:
INSERT INTO 表名 VALUES
(值1,值2,值3…值n),
(值1,值2,值3…值n),
(值1,值2,值3…值n);
4. 插入查询结果
语法:
INSERT INTO 表名(字段1,字段2,字段3…字段n)
SELECT (字段1,字段2,字段3…字段n) FROM 表2
WHERE …;
三、更新数据UPDATE
语法:
UPDATE 表名 SET
字段1=值1,
字段2=值2,
WHERE CONDITION;
示例:
UPDATE mysql.user SET password=password(‘123’)
where user=’root’ and host=’localhost’;
四、删除数据DELETE
语法:
DELETE FROM 表名
WHERE CONITION;
示例:
DELETE FROM mysql.user
WHERE password=’’;
第7章 单表查询
7.1 查询语法
SELECT 字段1,字段2... FROM 表名
WHERE 条件
GROUP BY field
HAVING 筛选
ORDER BY field
LIMIT 限制条数
7.2 关键字优先级
from 找哪个表
where 条件
group by 分组
having 筛选过滤
select
distinct 去重
order by 排序
limit 限制输出条数
7.3 实战
创建公司员工表,表的字段和数据类型
company.employee
员工id id int
姓名 name varchar
性别 sex enum
年龄 age int
入职日期 hire_date date
岗位 post varchar
职位描述 post_comment varchar
薪水 salary double
办公室 office int
部门编号 depart_id int
操作方法
#创建表,设置字段的约束条件
create table employee(
id int primary key 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 |
| 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 | |
| salart | double(15,2) | YES | | NULL | |
| office | int(11) | YES | | NULL | |
| depart_id | int(11) | YES | | NULL | |
+--------------+-----------------------+------+-----+---------+----------------+
rows in set (0.08 sec)
#插入记录
#三个部门:教学,销售,运营
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),
('xiaomage','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)
;
7.4 where
where子句中可以使用
1.比较运算符:>、<、>=、<=、<>、!=
2.between 80 and 100 :值在80到100之间
3.in(80,90,100)值是10或20或30
4.like 'xiaomagepattern': pattern可以是%或者_。%小时任意多字符,_表示一个字符
5.逻辑运算符:在多个条件直接可以使用逻辑运算符 and or not
例:
7.4.1 单条件查询
mysql> select id,emp_name from employee where id > 5;
+----+------------+
| id | emp_name |
+----+------------+
| 6 | jingliyang |
| 7 | jinxin |
| 8 | xiaomage |
| 9 | 歪歪 |
| 10 | 丫丫 |
| 11 | 丁丁 |
| 12 | 星星 |
| 13 | 格格 |
| 14 | 张野 |
| 15 | 程咬金 |
| 16 | 程咬银 |
| 17 | 程咬铜 |
| 18 | 程咬铁 |
7.4.2 多条件查询
mysql> select emp_name from employee where post='teacher' and salary>10000;
+----------+
| emp_name |
+----------+
| alex |
| jinxin |
+----------+
7.4.3 关键字BETWEEN AND
SELECT name,salary FROM employee
WHERE salary BETWEEN 10000 AND 20000;
SELECT name,salary FROM employee
WHERE salary NOT BETWEEN 10000 AND 20000;
#注意''是空字符串,不是null
SELECT name,post_comment FROM employee WHERE post_comment='';
ps:
执行
update employee set post_comment='' where id=2;
再用上条查看,就会有结果了
7.4.4 关键字IN集合查询
mysql> SELECT name,salary FROM employee WHERE salary=3000 OR salary=3500 OR salary=4000 OR salary=9000 ;
+------------+---------+
| name | salary |
+------------+---------+
| yuanhao | 3500.00 |
| jingliyang | 9000.00 |
+------------+---------+
rows in set (0.00 sec)
mysql> SELECT name,salary FROM employee WHERE salary IN (3000,3500,4000,9000) ;
+------------+---------+
| name | salary |
+------------+---------+
| yuanhao | 3500.00 |
| jingliyang | 9000.00 |
+------------+---------+
mysql> SELECT name,salary FROM employee WHERE salary NOT IN (3000,3500,4000,9000) ;
+-----------+------------+
| name | salary |
+-----------+------------+
| egon | 7300.33 |
| alex | 1000000.31 |
| wupeiqi | 8300.00 |
| liwenzhou | 2100.00 |
| jinxin | 30000.00 |
| xiaomage | 10000.00 |
| 歪歪 | 3000.13 |
| 丫丫 | 2000.35 |
| 丁丁 | 1000.37 |
| 星星 | 3000.29 |
| 格格 | 4000.33 |
| 张野 | 10000.13 |
| 程咬金 | 20000.00 |
| 程咬银 | 19000.00 |
| 程咬铜 | 18000.00 |
| 程咬铁 | 17000.00 |
+-----------+------------+
rows in set (0.00 sec)
7.4.5 关键字LIKE模糊查询
通配符’%’
mysql> SELECT * FROM employee WHERE name LIKE 'jin%';
+----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
| id | name | sex | age | hire_date | post | post_comment | salary | office | depart_id |
+----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
| 6 | jingliyang | female | 18 | 2011-02-11 | teacher | NULL | 9000.00 | 401 | 1 |
| 7 | jinxin | male | 18 | 1900-03-01 | teacher | NULL | 30000.00 | 401 | 1 |
+----+------------+--------+-----+------------+---------+--------------+----------+--------+-----------+
rows in set (0.00 sec)
通配符'_'
mysql> SELECT age FROM employee WHERE name LIKE 'ale_';
+-----+
| age |
+-----+
| 78 |
+-----+
row in set (0.00 sec)
7.4.6 练习:
1. 查看岗位是teacher的员工姓名、年龄
2. 查看岗位是teacher且年龄大于30岁的员工姓名、年龄
3. 查看岗位是teacher且薪资在9000-1000范围内的员工姓名、年龄、薪资
4. 查看岗位描述不为NULL的员工信息
5. 查看岗位是teacher且薪资是10000或9000或30000的员工姓名、年龄、薪资
6. 查看岗位是teacher且薪资不是10000或9000或30000的员工姓名、年龄、薪资
7. 查看岗位是teacher且名字是jin开头的员工姓名、年薪
#对应的sql语句
select name,age from employee where post = 'teacher';
select name,age from employee where post='teacher' and age > 30;
select name,age,salary from employee where post='teacher' and salary between 9000 and 10000;
select * from employee where post_comment is not null;
select name,age,salary from employee where post='teacher' and salary in (10000,9000,30000);
select name,age,salary from employee where post='teacher' and salary not in (10000,9000,30000);
select name,salary*12 from employee where post='teacher' and name like 'jin%';
7.5 group by 分组查询
7.5.1 使用说明
#1、首先明确一点:分组发生在where之后,即分组是基于where之后得到的记录而进行的
#2、分组指的是:将所有记录按照某个相同字段进行归类,比如针对员工信息表的职位分组,或者按照性别进行分组等
#3、为何要分组呢?
取每个部门的最高工资
取每个部门的员工数
取男人数和女人数
小窍门:‘每’这个字后面的字段,就是我们分组的依据
#4、大前提:
可以按照任意字段分组,但是分组完毕后,比如group by post,只能查看post字段,如果想查看组内信息,需要借助于聚合函数
7.5.2 参数设置
设置sql模式为 ONLY_FULL_GROUP_BY
set global sql_mode='ONLY_FULL_GROUP_BY';
#查看MySQL 5.7默认的sql_mode如下:
mysql> select @@global.sql_mode;
+--------------------+
| @@global.sql_mode |
+--------------------+
| ONLY_FULL_GROUP_BY |
+--------------------+
1 row in set (0.00 sec)
#设置成功后,一定要退出,然后重新登录方可生效
mysql> exit;
Bye
7.6 聚合函数
max()求最大值
min()求最小值
avg()求平均值
sum() 求和
count() 求总个数
7.6.1 实战练习
#强调:聚合函数聚合的是组的内容,若是没有分组,则默认一组
# 每个部门有多少个员工
select post,count(id) from employee group by post;
# 每个部门的最高薪水
select post,max(salary) from employee group by post;
# 每个部门的最低薪水
select post,min(salary) from employee group by post;
# 每个部门的平均薪水
select post,avg(salary) from employee group by post;
# 每个部门的所有薪水
select post,sum(age) from employee group by post;
7.7 having
7.7.1 用法
having发生在分组group by 之后,因而having中可以使用分组的字段,无法直接取到其他字段,可以使用聚合函数
执行顺序为:where > grooup by > having
7.7.2 having/where的区别
where发生在分组group by 之前,因而where中可以有任意字段,但是绝对不能使用聚合函数。
7.7.3 实战练习
验证:
mysql> select * from employee where salary>1000000;
+----+------+------+-----+------------+---------+--------------+------------+--------+-----------+
| id | name | sex | age | hire_date | post | post_comment | salary | office | depart_id |
+----+------+------+-----+------------+---------+--------------+------------+--------+-----------+
| 2 | alex | male | 78 | 2015-03-02 | teacher | | 1000000.31 | 401 | 1 |
+----+------+------+-----+------------+---------+--------------+------------+--------+-----------+
row in set (0.00 sec)
mysql> select * from employee having salary>1000000;
ERROR 1463 (42000): Non-grouping field 'salary' is used in HAVING clause
# 必须使用group by才能使用group_concat()函数,将所有的name值连接
mysql> select post,group_concat(name) from emp group by post having salary > 10000; ##错误,分组后无法直接取到salary字段
ERROR 1054 (42S22): Unknown column 'post' in 'field list'
1. 查询各岗位内包含的员工个数小于2的岗位名、岗位内包含员工名字、个数
mysql> select post,group_concat(name),count(id) from employee group by post having count(id)<2;
+-----------------------------------------+--------------------+-----------+
| post | group_concat(name) | count(id) |
+-----------------------------------------+--------------------+-----------+
| 老男孩驻沙河办事处外交大使 | egon | 1 |
+-----------------------------------------+--------------------+-----------+
1 row in set (0.00 sec)
2. 查询各岗位平均薪资大于10000的岗位名、平均工资
mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000;
+-----------+---------------+
| post | avg(salary) |
+-----------+---------------+
| operation | 16800.026000 |
| teacher | 151842.901429 |
+-----------+---------------+
2 rows in set (0.00 sec)
3. 查询各岗位平均薪资大于10000且小于20000的岗位名、平均工资
mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000 and avg(salary) <20000;
+-----------+--------------+
| post | avg(salary) |
+-----------+--------------+
| operation | 16800.026000 |
+-----------+--------------+
1 row in set (0.00 sec)
7.8 order by 查询排序
7.8.1 用法
按单列排序
SELECT * FROM employee ORDER BY age;
SELECT * FROM employee ORDER BY age ASC;
SELECT * FROM employee ORDER BY age DESC;
按多列排序:先按照age升序排序,如果年纪相同,则按照id降序
SELECT * from employee
ORDER BY age ASC,
id DESC;
7.8.2 实战练习
SELECT * from employee ORDER BY age ASC,id DESC;
mysql> SELECT * from employee ORDER BY age ASC,id DESC;
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| id | name | sex | age | hire_date | post | post_comment | salary | office | depart_id |
+----+------------+--------+-----+------------+-----------------------------------------+--------------+------------+--------+-----------+
| 18 | 程咬铁 | female | 18 | 2014-05-12 | operation | NULL | 17000.00 | 403 | 3 |
| 17 | 程咬铜 | male | 18 | 2015-04-11 | operation | NULL | 18000.00 | 403 | 3 |
| 16 | 程咬银 | female | 18 | 2013-03-11 | operation | NULL | 19000.00 | 403 | 3 |
| 15 | 程咬金 | male | 18 | 1997-03-12 | operation | NULL | 20000.00 | 403 | 3 |
| 12 | 星星 | female | 18 | 2016-05-13 | sale | NULL | 3000.29 | 402 | 2 |
| 11 | 丁丁 | female | 18 | 2011-03-12 | sale | NULL | 1000.37 | 402 | 2 |
| 7 | jinxin | male | 18 | 1900-03-01 | teacher | NULL | 30000.00 | 401 | 1 |
练习题:
查询各岗位平均薪资大于10000的岗位名、平均工资,结果按平均薪资降序排列
mysql> select post,avg(salary) from employee group by post having avg(salary) > 10000 order by avg(salary) desc;
+-----------+---------------+
| post | avg(salary) |
+-----------+---------------+
| teacher | 151842.901429 |
| operation | 16800.026000 |
+-----------+---------------+
2 rows in set (0.00 sec)
查询所有员工信息,先按照age升序排序,如果age相同则按照hire_date降序排序
select * from employee ORDER BY age asc,hire_date desc;
7.9 limit
7.9.1 用法:
SELECT * FROM employee ORDER BY salary DESC
LIMIT 3; #默认初始位置为0
SELECT * FROM employee ORDER BY salary DESC
LIMIT 0,5; #从第0开始,即先查询出第一条,然后包含这一条在内往后查5条
SELECT * FROM employee ORDER BY salary DESC
LIMIT 5,5; #从第5开始,即先查询出第6条,然后包含这一条在内往后查5条
7.9.2 实战练习
# 第2页数据
mysql> select * from employee limit 5,5;
# 第1页数据
mysql> select * from employee limit 0,5;
第8章 多表查询
准备工作:准备两张表,部门表(department)、员工表(employee)
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 | |
+-------+-------------+------+-----+---------+-------+
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 | |
+--------+-----------------------+------+-----+---------+----------------+
rows in set (0.01 sec)
mysql> select * from department;
+------+--------------+
| id | name |
+------+--------------+
| 200 | 技术 |
| 201 | 人力资源 |
| 202 | 销售 |
| 203 | 运营 |
+------+--------------+
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 |
+----+----------+--------+------+--------+
rows in set (0.00 sec)
8.1 多表链接查询
8.1.1 要求:
要查询的员工信息以及该员工所在的部门。从该题中,我们看出既要查员工又要查该员工的部门,肯定要将两张表进行连接查询,多表连接查询。
8.1.2 重点:外链接语法
语法:
SELECT 字段列表
FROM 表1 INNER|LEFT|RIGHT JOIN 表2
ON 表1.字段 = 表2.字段;
(1)先看第一种情况交叉连接:不适用任何匹配条件。生成笛卡尔积
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 | 运营 |
(2)内连接:只连接匹配的行
#找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了匹配的结果
#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 | 技术 |
+----+---------+------+--------+--------------+
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;
(3)外链接之左连接:优先显示左表全部记录
#以左表为准,即找出所有员工信息,当然包括没有部门的员工
#本质就是:在内连接的基础上增加左边有,右边没有的结果
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 |
+----+----------+--------------+
rows in set (0.00 sec)
(4) 外链接之右连接:优先显示右表全部记录
#以右表为准,即找出所有部门信息,包括没有员工的部门
#本质就是:在内连接的基础上增加右边有,左边没有的结果
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 | 运营 |
+------+---------+--------------+
rows in set (0.00 sec)
(5) 全外连接:显示左右两个表全部记录(了解)
#外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果
#注意: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 | 运营 |
+------+----------+--------+------+--------+------+--------------+
rows in set (0.01 sec)
#注意 union与union all的区别:union会去掉相同的纪录
8.2 符合条件链接查询
例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;
+---------+--------------+
| name | name |
+---------+--------------+
| alex | 人力资源 |
| wupeiqi | 人力资源 |
| yuanhao | 销售 |
+---------+--------------+
3 rows in set (0.00 sec)
select employee.id,employee.name,employee.age,department.name from employeement where employee.dep_id = department.id and age >25 order by age asc;
8.3 子查询
8.3.1 作用
#1:子查询是将一个查询语句嵌套在另一个查询语句中。
#2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。
#3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字
#4:还可以包含比较运算符:= 、 !=、> 、<等
8.3.2 实战练习
(1)带in关键字的子查询
#查询平均年龄在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);
(2)带比较运算符的子查询
#比较运算符:=、!=、>、>=、<、<=、<>
#查询大于所有人平均年龄的员工名与年龄
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 |
(3)带EXISTS关键字的子查询
#EXISTS关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录。而是返回一个真假值。True或False
#当返回True时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询
#department表中存在dept_id=203,Ture
mysql> select * from employee where exists (select id from department where id=200);
+----+----------+--------+------+--------+
| id | name | sex | age | dep_id |
+----+----------+--------+------+--------+
| 1 | egon | male | 18 | 200 |
| 2 | alex | female | 48 | 201 |
| 3 | wupeiqi | male | 38 | 201 |
| 4 | yuanhao | female | 28 | 202 |
| 5 | 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)
8.3.3 练习:查询每个部门最新入职的那位员工
#创建表
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)
;
方法:
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;
第9章 pymysql
9.1 介绍
python 中操作数据库使用pymysql模块,该模块本质就是一个套接字客户端软件,使用前需要事先安装
9.2 本地安装方法
9.2.1 装模块
pip3 install pymysql
9.2.2 mysql创建库
create database db8;
9.2.3 创建表
create table userinfo(
id int primary key auto_increment,
name char(16) not null,
pwd int
);
9.2.4 插入数据
insert from userinfo(name,pwd) values('wang',123),
('li',456);
9.3 pymysql模块使用
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
user = input('>> 请输出primary 用户名:')
pwd2 = input('>> 请输入密码:')
conn = pymysql.connect(
host='127.0.0.1',
user='root',
password='',
db='db8',
charset='utf8'
)
# 创建光标
cursor = conn.cursor()
sql = "select * from userinfo where name='%s' and pwd= '%s'" %(user,pwd2)
# print(sql)
# 执行sql语句
cursor.execute(sql)
result = cursor.execute(sql)
print(result)
# 关闭数据库连接
cursor.close()
conn.close()
#判断查询密码用户名是否正确
if result:
print('登录成功')
else:
print('登录失败')
输出:
C:\python3\python3.exe D:/python/untitled2/pytho_17/mysql.py
>> 请输出primary 用户名:li
>> 请输入密码:4567
0
登录失败
9.4 execute()之sql注入
9.4.1 两种注入方式
1)sql注入之:用户存在,绕过密码
wang' -- 任意字符
说明:不用输入密码利用注释将系统骗过
C:\python3\python3.exe D:/python/untitled2/pytho_17/mysql.py
>> 请输出primary 用户名:wang'-- adfafdf
>> 请输入密码:
1
登录成功
2)sql注入之:用户不存在,绕过用户与密码
xxx' or 1=1 -- 任意字符
9.4.2 execute()解决方法
1)列表
#改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)
sql="select * from userinfo where name=%s and password=%s" #!!!注意%s需要去掉引号,因为pymysql会自动为我们加上
result=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来
例:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
user = input('>> 请输出用户名:')
pwd2 = input('>> 请输入密码:')
conn = pymysql.connect(
host='127.0.0.1',
user='root',
password='',
db='db8',
charset='utf8'
)
# 创建光标
cursor = conn.cursor()
sql = "select * from userinfo where name = %s and pwd= %s"
result = cursor.execute(sql,[user,pwd2])
print(result)
# 关闭数据库连接
cursor.close()
conn.close()
#判断查询密码用户名是否正确
if result:
print('登录成功')
else:
print('登录失败')
2)字典的形式解决:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
user = input('>> 请输出用户名:')
pwd2 = input('>> 请输入密码:')
conn = pymysql.connect(
host='127.0.0.1',
user='root',
password='',
db='db8',
charset='utf8'
)
# 创建光标
cursor = conn.cursor()
sql = "select * from userinfo where name = %(name)s and pwd= %(pwd)s"
result = cursor.execute(sql,{"name":user,"pwd":pwd2})
print(result)
# 关闭数据库连接
cursor.close()
conn.close()
#判断查询密码用户名是否正确
if result:
print('登录成功')
else:
print('登录失败')
9.5 插入
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
user = input('>> 请输出用户名:')
pwd2 = input('>> 请输入密码:')
conn = pymysql.connect(
host='127.0.0.1',
user='root',
password='',
db='db8',
charset='utf8'
)
# 创建光标
cursor = conn.cursor()
sql = "insert into userinfo(name,pwd) values(%s,%s)"
result = cursor.execute(sql,[user,pwd2])
print(result)
#插入多条
cursor.executemany(sql,[('lisi','110'),('wangwu','119')])
#插入数据要commit
conn.commit()
# 关闭数据库连接
cursor.close()
conn.close()
#判断查询密码用户名是否正确
if result:
print('登录成功')
else:
print('登录失败')
9.6 改
# sql = "update userinfo set username = %s where id = 2"
# effect_row = cursor.execute(sql,username)
# print(effect_row)
9.7 删
sql = "delete from userinfo where id = 2"
effect_row = cursor.execute(sql)
print(effect_row)
9.8 插入删除更新要commit
#插入数据要commit
conn.commit()
# 关闭数据库连接
cursor.close()
conn.close()
9.9 查询
方法:
fetchone():获取下一行数据,第一次为首行;
fetchall():获取所有行数据源
fetchmany(4):获取4行数据
9.9.1 fetchone()
import pymysql
# 1.连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8')
# 2.创建游标
cursor = conn.cursor()
sql = 'select * from userinfo'
cursor.execute(sql)
# 查询第一行的数据
row = cursor.fetchone()
print(row) # (1, 'mjj', '123')
# 查询第二行数据
row = cursor.fetchone()
print(row) # (3, '张三', '110')
# 4.关闭游标
cursor.close()
# 5.关闭连接
conn.close()
9.9.2 fetchall()
import pymysql
# 1.连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8')
# 2.创建游标
cursor = conn.cursor()
sql = 'select * from userinfo'
cursor.execute(sql)
# 获取所有的数据
rows = cursor.fetchall()
print(rows)
# 4.关闭游标
cursor.close()
# 5.关闭连接
conn.close()
#运行结果
((1, 'mjj', '123'), (3, '张三', '110'), (4, '李四', '119'))
9.9.3 fetchmany():
import pymysql
# 1.连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8')
# 2.创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = 'select * from userinfo'
cursor.execute(sql)
# 获取2条数据
rows = cursor.fetchmany(2)
print(rows)
# 4.关闭游标
# rows = cursor.fetchall()
# print(rows)
cursor.close()
# 5.关闭连接
conn.close()
#结果如下:
[{'id': 1, 'username': 'mjj', 'pwd': '123'}, {'id': 3, 'username': '张三', 'pwd': '110'}]
9.10 查询结果转换
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) #在实例化的时候,将属性cursor设置为pymysql.cursors.DictCursor
9.11 指针控制
在fetchone示例中,在获取行数据的时候,可以理解开始的时候,有一个行指针指着第一行的上方,获取一行,它就向下移动一行,所以当行指针到最后一行的时候,就不能再获取到行的内容,所以我们可以使用如下方法来移动行指针:
cursor.scroll(1,mode='relative') # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动
第一个值为移动的行数,整数为向下移动,负数为向上移动,mode指定了是相对当前位置移动,还是相对于首行移动
9.12 实战练习
# 1.Python实现用户登录
# 2.Mysql保存数据
import pymysql
# 1.连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8')
# 2.创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = 'select * from userinfo'
cursor.execute(sql)
# 查询第一行的数据
row = cursor.fetchone()
print(row) # (1, 'mjj', '123')
# 查询第二行数据
row = cursor.fetchone() # (3, '张三', '110')
print(row)
cursor.scroll(-1,mode='relative') #设置之后,光标相对于当前位置往前移动了一行,所以打印的结果为第二行的数据
row = cursor.fetchone()
print(row)
cursor.scroll(0,mode='absolute') #设置之后,光标相对于首行没有任何变化,所以打印的结果为第一行数据
row = cursor.fetchone()
print(row)
# 4.关闭游标
cursor.close()
# 5.关闭连接
conn.close()
#结果如下
{'id': 1, 'username': 'mjj', 'pwd': '123'}
{'id': 3, 'username': '张三', 'pwd': '110'}
{'id': 3, 'username': '张三', 'pwd': '110'}
{'id': 1, 'username': 'mjj', 'pwd': '123'}
第10章 索引
参考地址:https://www.cnblogs.com/majj/p/9196025.html
第11章 localstore
11.1 永久存储
解释:设置并追加值
//一开始加载页面的时候检查 你的localstoragre是否有key
if (localStorage.getItem('user')) {
var user = localStorage.getItem('user');
$('<p></p>').appendTo('.content').text(user);
}
//设置值
$('#submit').click(function () {
sessionStorage.setItem()
})
11.2 会话存储
$('#submit').click(function () {
sessionStorage.setItem()
})
11.3 cookie存储原理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="box">
<input type="text" name="user" id="user">
<input type="button" value="提交" id="submit">
</div>
<div class="content">
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function () {
if (localStorage.getItem('user')){
var user = localStorage.getItem('user');
$('<p></p>').appendTo('.content').text(user);
}
$('#submit').click(function () {
var user = $('#user').val();
console.log(user);
// 没添加一条都存在页面上显示
$('<p></p>').appendTo('.content').text(user);
$('#user').val('');
localStorage.setItem('user',user);
})
})
</script>
</body>
</html>
11.4 localStorage
localStorage.getItem() 获取值
localStorage.setItem() 设置值
localStorage.removeItem() 移除值
localStorage.clear() 清空
11.5 session会话的存储
sessionStorage.getItem()
sessionStorage.setItem()
sessionStorage.removeItem()
sessionStorage.clear()
create table dt1(
id int primary key auto_increment ,
name varchar(20) not null,
pwd varchar(50) not null
);
insert into dt1(name,pwd) values
('simayi',123456),
('lili',123456);