一文读懂MySQL

MySQL

一、进入MySQL数据库

mysql -h主机名 -u用户名 -p密码

mysql -hlocalhost -uroot -p123456

简化

mysql -uroot -p

对于库和表的常用语句

查看所有库

show databases;

选择库

use 库名;

查看当前库下所有的表

show tables;

删除库

drop database 库名;

删除表

drop table 表名;

退出数据库

  1. \q
  2. exit
  3. quit

创建库 并设置字符编码

create database 库名 character set utf8;

撤销当前命令

\c

竖状查看语句

\G

查看创建库语句

show create database 库名

查看创表语句

show create table 表名

查看当前所在数据库

select database();

查看表结构

desc 表名

清空表(会将自增归位)

truncate 表名

注意:

  1. 在终端下 mysql的命令是不区分大小写的
  2. 库名表名也不区分 但是在Linux下区分
  3. 我们当前MySQL数据库是严谨报错(只要有任何的问题都会报错)
  4. 如果没有设置字段not null 则默认为null

二、MySQL表的创建

字段类型

(1) 数值类型

类型 大小 范围 无符号 用途
tinyint 1字节 -128,127 255 小整数值
smallint 2字节 -32768,32767 65535 大整数值
int 4字节 0,4九位数 大整数值
float 4字节 单精度浮点型
double 8字节 双精度浮点型
decimal 小数值(更加精准)

实例

mysql> create table testint(

-> ti tinyint,
-> si smallint,
-> timestamp int,
-> fl float(6,2),
-> db double(6,2),
-> money decimal(6,2)
-> );

插入数据

insert into testint values(120,20000,1234567891,1234,1234,1234);
Query OK, 1 row affected (0.00 sec)

注意:

  1. 当给float/double/decimal 小数点的长度超出范围 则会四舍五入

  2. int/tinyint 后面默认的长度会在原有的基础上+1(那一位是符号位) 如果手动给定数值类型的后面的长度 是无意义的 只有配合zerofill的时候 才会有意义(只有配合0填充的时候) 因为除了这个你是限制不了值的长度范围的

    int(3) zerofill 有意义

    int(3) 无意义的

(2) 时间类型

类型 大小 范围 格式 用途
date 3 10000-01-01/9999-12-31 YYYY-MM-DD 日期值
time 3 838:59:59 HH:MM:SS 存储时间值
year 1 1901-2155 YYYY 年份值
datetime 8 10000-01-01 00:00:00/9999-12-31 23:59:59 YYYY-MM-DD HH:MM:SS 混合日期
timestamp 4 YYYYMMDDHHMMSS 时间戳

实例

mysql> create table mytime(
-> mdate date,
-> mtime time,
-> myear year,
-> mdatetime datetime,
-> mtimestamp timestamp
-> );

插入数据

mysql> insert into mytime values('2019-12-24','20:55:00',2019,now(),1000000000);

注意:

  1. timestamp类型自动获取当前的时间戳
  2. 在存储的时候最好存储时间戳 这样服有利于我们对时间的计算

(3) 字符串类型

类型 大小 用途
char 0-255字节 定长字符串
varchar 0-255字节 可变长度
blob 0-65535字节 存储二进制
text 0-65535 存储长文本
longtext 0-4(10位长度) 超长/极大文本数据
enum 65535个成员 枚举 只能选择其中的一个
set 64个成员 可选择多个成员 用逗号隔开

实例

mysql> create table mystr(
-> mchar char(11),
-> mvarchar varchar(12),
-> mtext text,
-> mlongtext longtext,
-> menum enum('w','m'),
-> mset set('w','m','ry')
-> );

插入数据

mysql> insert into mystr values('12345678','yang','博客','博客','w','m');

注意事项:

  1. char和varchar的区别
    • varchar要比char更节省空间
    • char和varchar存储值的长度都在0~255之间
    • char的执行效率要高于varchar
  2. 枚举只能选择一个成员 set可以选择多个成员(成员出现重复的 则可以自动去重)

三、字段约束

  1. 无符号

    unsigned 只能设置数值类型 当设置完以后 存储长度扩大一倍 不允许有符号出现

  2. 零填充

    zerofill 只能用于数值类型 在实际长度没有满足时 会自动用0补位

  3. 自增

    auto_increment 用于主键索引 每当多一条数据 自增会自动+1

  4. 默认值

    default 如果不设置 默认为null 如果给了默认值 则值为你给定的默认值(当前字段没有给值)

  5. null和not null

    默认为null 当不给插入值的时候 默认为null

    not null 当设置值为not null的时候 该字段必须给值

  6. 字段说明

    comment 给字段添加字段说明

实例

mysql> create table user(
    -> id int unsigned primary key auto_increment,
    -> age tinyint(3) zerofill not null,
    -> hobby varchar(200) default '青青草原我最狂',
    -> sex enum('w','m'),
    -> username varchar(12) comment '喜羊羊'
    -> );

插入数据

mysql> insert into user values(null,18,'吃草','w','yang');

null值的注意事项

  1. null值意味着空值或者没有值
  2. 不能对null值进行运算 因为运算结果还是为null
  3. 0或者null 都意味着假 其余值都为真

四、索引

在MySQL数据库中 主要有4种索引

  1. primary key 主键索引
  2. unique 唯一索引
  3. index 常规索引
  4. fulltext 全文索引

(1) 主键索引

主键索引是关系型数据库中最常见的索引类型 作用主要是确定一个表中数据所在的记录位置 我们可以添加primary key 将字段设置为主键索引

注意:

  1. 最好每张表都要有一个主键索引 但不是必须指定的
  2. 一个表只能指定一个主键索引 而且主键索引的值不能为null!
  3. 主键索引可以有多个候选索引(not null/auto_increment)

实例

mysql> create table testprimary(
-> id int unsigned primary key auto_increment,
-> username varchar(20)
-> );

将自增归位

mysql> alter table testprimary auto_increment=1;

(2) 唯一索引

唯一索引与主键索引一样 都可以防止创建重复的值 但是不同的是 一个表中只能有一个主键索引 但是可以有多个唯一索引 我们使用关键字unique来设置唯一索引

实例

mysql> create table testunique(
    -> id int unsigned primary key auto_increment,
    -> username varchar(20) unique
    -> );

单独添加唯一索引

mysql> create table testunique(
    -> id int unsigned primary key auto_increment,
    -> username varchar(20),
    -> unique myunique(username)
    -> );

注意

  1. 唯一索引的位置 和所要给添加的字段的位置是没关联的

  2. 索引名称默认为字段名

  3. 实例2是给唯一索引起一个索引名 叫myunique

  4. 当给唯一索引添加了重复的数据 则会报错

    Duplicate entry ‘lucky’ for key ‘myunique’

(3) 常规索引

常规索引 是关系型数据库中 查询最重要的技术 如果要提升数据库的性能 索引是优先该考虑的 因为它能使数据库得到最大性能方面的提升

实例

使用index创建常规索引

mysql> create table testindex(
    -> id int unsigned primary key auto_increment,
    -> username varchar(20),
    -> age tinyint unsigned,
    -> unique(username), //添加唯一索引
    -> index(age) //添加常规索引
    -> );

使用key创建常规索引

mysql> create table testindex(
    -> id int primary key auto_increment,
    -> username varchar(20),
    -> key(username)
    -> );

将常规索引 唯一索引 添加到同一个字段上

mysql> create table testindex(
    -> id int unsigned primary key auto_increment,
    -> username varchar(20),
    -> age tinyint unsigned,
    -> unique(username),
    -> index(username)
    -> );

创建表 并起名字

mysql> create table testindex(
    -> id int unsigned primary key auto_increment,
    -> username varchar(20),
    -> age tinyint unsigned,
    -> unique uusername(username),
    -> index iusername(username)
    -> );

查看表结构

       Table: testindex
Create Table: CREATE TABLE `testindex` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `age` tinyint(3) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`),
  KEY `username_2` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

注意:

常规索引的缺点

  1. 多占用磁盘空间
  2. 会减慢 插入 修改 和删除的操作

创建常规索引 可以使用关键字 index 或者 key 来去创建

(4) 全文索引

alter table 表名 addfulltext 索引名称(索引字段)

全文索引只能用在myisam表引擎的表中 并且只能在char、varchar或者 text字段类型中创建 全文索引是不支持中文的

五、表存储引擎

表中有很多种存储引擎 其中俩种最为重要 innoDB和MyISAM:

  1. MyISAM数据表类型的特点十成熟 稳定易于管理
  2. MyISAM不支持事物处理 innodb支持
  3. MyISAM不支持外键 innodb支持
  4. MyISAM引擎的表的效率最高
  5. MyISAM表类型会产生二个文件 innodb只会产生一个文件

六、不同引擎的存储区别

.frm文件: 存储数据表的框架结构 文件与表名相同 每一个表对应一个 .frm文件

MyISAM表文件

MYD 即my data 表数据文件

MYI 即my index 索引文件

InnoDB表文件

ibd文件: 单表表空间文件 存放用户的数据和索引的文件

七、innodb的事物处理

(1) 查询是否为自动提交

select @@autocommit 如果值为1 则自动提交 0为手动提交

(2) 更改为手动提交

set autocommit=0

(3) 开启事物

begin;

(4) 执行SQL语句

增删改查…

(5) 提交或回滚

commit work

rollback work

注意:

  1. 如果数据库开启了事物 对数据进行操作完以后 没有提交回滚 直接退出 则为回滚(也就是没有保存刚才的操作)
  2. 只有innodb才支持事物 MyISAM不支持

八、对于表结构的操作

  1. 给表添加一个字段

    格式

    alter table 表名 add 字段名称 字段类型 约束条件

    实例

    mysql> alter table user add hobby varchar(20) default '爱好';
    

    添加的字段默认排在最后

  2. 添加字段更改字段位置

    格式

    alter table 表名 add 字段名称 字段类型 约束条件 after 字段名 (把新字段放在某个字段的后面)

    alter table 表名 add 字段名称 字段类型 约束条件 first (把新字段放在首位)

    实例

    mysql> alter table user add hobby varchar(20) default '爱好' after username;
    在username字段后面创建一个新字段 叫 hobby
    mysql> alter table user add hobby varchar(20) default '爱好' first;
    
  3. 删除一个字段

    格式

    alter table 表名 drop 字段名

    实例

    mysql> alter table user drop tid;
    删除 tid 字段
    
  4. 更改字段名

    格式

    alter table 表名 chang 旧字段名 新字段名 字段类型 [约束条件 [after/first]]

    实例

    mysql> alter table user change password hash_password varchar(128);
    将password字段名 更改为 hash_password
    
  5. 更改字段类型和约束条件

    格式

    alter table 表名 modify 字段名 字段类型 [约束条件 [after/first]]

    实例

    mysql> alter table user modify hash_password char(128);
    
  6. 添加索引

    格式

    alter table 表名 add 索引类型(索引字段)

    alter table 表名 add 索引类型 索引名(索引字段)

    实例

    mysql> alter table user add unique(hobby);
    mysql> alter table user add index(sex);
    mysql> alter table user add index i_sex(sex);
    
  7. 删除索引

    格式

    alter table 表名 drop key 索引名称

    实例

    mysql> alter table user drop key hobby;
    
  8. 查看表中的索引

    格式

    show index from 表名

  9. 修改表的字符编码

    格式

    alter table 表名 character set utf8;

  10. 更改字段编码

格式

alter table 表名modify 字段名 字段类型 约束条件 character set utf8;

  1. 表结构复制

格式

create table A like B;

实例

   mysql> alter table user drop key hobby;

九、数据添加 inset

  1. 指定字段添加值

    insert into 表名(字段名,…) values(值…)

    字段和值是一一对应的

    注意:如果有的值 not null 需要设置值 否则报错

    实例

    insert into user(username,hash_password,sex,age,hobby) values('yang','123456','w',30,'吃草');
    
  2. 不指定字段添加值

    insert into 表名 values(值,)

    注意:

    所有的 字段都必须给值 值和表中的字段是一一对应的

    实例

    insert into user values(null,'yang321','abcdefg','m',20,'弹吉他');
    
  3. 指定字段添加多个值

    insert into 表名(字段…) values(值,…),(值,…)…

    实例

    insert into user(username,hash_password,sex,age,hobby) values('张三','123456789','w',22,'打王者'),('李四','abcdefg','m',30,'英雄联盟');
    
  4. 不指定字段添加多个值

    insert into 表名 values(值,…),(值,…)

    实例

    insert into user values(null,'张三','123456789','w',22,'打王者'),(null,'李四','abcdefg','m',30,'英雄联盟');
    

十、数据查询 select

  1. 不指定字段查询(不建议)

    select * from 表名

    实例

    select * from user;
    
  2. 指定字段查询

    select 字段名,字段名… from 表名

    实例

    select username,sex,age from user;
    
  3. 给查询的age字段值 +1

    select age+1 from user;

  4. 给字段起别名 可以用as关键字 或者 使用空格隔开 一样的

    select age+1 as newage from user;

    select age+1 newage from user;

十一、查询条件 where

(1) 比较运算符

  1. >

    select * from user where id > 2;

  2. <

    select * from user where id < 2;

  3. >=

    select * from user where id >= 2;

  4. <=

    select * from user where id<=2;

  5. !=/<>

    select * from user where id != 2;

  6. =

    select * from user where id=2;

(2) 逻辑运算符

  1. and 并且 俩侧为真才为真

    select * from user where age>=18 and sex=‘w’;

  2. or 或 一侧为真 就为真

    select * from user where age>=18 or sex=‘w’;

  3. between … and … 在…之间

    select * from user where age between 16 and 30; == select * from user where age>=16 and age<=30;

    包含 16 和 30的本身

  4. not between … and … 不在…之间

    select * from user where age not between 16 and 30; == select * from user where age<17 or age>30;

  5. in 在…范围

    select * from user where age in(18,20,100); == select * from user where age=18 or age=20 or age=100;

  6. not … in … 不在…范围内

    select * from user where age not in(18,20,100);

(3) 子查询 (查询的条件还是一条sql语句)

select * from user where age in(select age from user where id between 2 and 4);

(4) 排序

  1. 升序(默认为升序) asc

    select … order by 字段名;

    select … order by 字段名 asc;

    实例

    select * from user order by age asc;
    select * from user order by age;
    
  2. 降序 (desc)

    select … order by 字段名 desc;

    实例

    select * from user order by age desc;
     select * from user where age>18 and age <30 order by age desc;
    

(5) is is not

实例

select * from user where hash_password is null;
select * from user where hash_password is not null;

注意:

因为 null 是一个特殊的值 需要用is 或者 is not 进行操作

(6) limit 取值

select * from user limit 5; 从0开始取5条数据

select * from user limit 5,5; 从第5条开始 取5条数据

wher和order by 以及 limit的组合使用

select * from user where sex = 'w' order by age desc limit 1;

(7) 模糊查询 like

  1. ‘%值%’ 包含查询 模糊查询

    select * from user where username like ‘%lucky%’ and sex=‘w’;

  2. ‘值%’ 以值作为开头

    select * from user where username like ‘张%’;

  3. ‘%值’ 以值作为结尾

    select * from user where username like ‘%张’;

(8) 聚合函数

  1. count() 统计
  2. max() 最大
  3. min() 最小
  4. sum() 求和
  5. avg() 平均数

select count(*),max(age),min(age),sum(age),avg(age) from user;

(9) 分组 group by

统计男和女分别有多少人

select sex,count(*) as count from user group by sex

查询每个班级有多少人

select class,count(*) from user group by class;

查询每个班级中的男生和女生分别有多少人

select class,sex,count(*) from user group by class,sex;

子句 having 相当于where

select class,count(*) as p from user group by class having p>2;

select class,count(*) as p from user group by class having class=‘online3’;

十二、删除 delete

主体结构

delete from 表名 where 条件

删除 密码为null的数据

delete from user where hash_password is null;

注意:

一定添加 where条件 否则 删除所有

十三、修改update

主体结构

update 表名 set 字段名=值,字段名=值… where 条件

实例

所有年龄+1

update user set age=age+1;

注意:

如果不添加where条件 则修改所有

十四、多表联查

(1) 隐式内连接

select * from goods g,user u where u.id=g.uid
select u.id,u.username,g.goodsname from goods g,user u where u.id=g.uid and g.uid=1

(2) 显示内连接 inner … join …

select u.id,u.username,g.goodsname from goods g INNER JOIN user u ON u.id=g.uid and g.uid=1

(3) 左连接 left … join …

select u.id,u.username,g.goodsname from goods g LEFT JOIN user u ON u.id=g.uid and g.uid=1

注意:

left … join … 以左表为主表 右表为辅表 会将主表数据 全都查询出来

(4) 右连接 right … join …

select u.id,u.username,g.goodsname from goods g RIGHT JOIN user u ON u.id=g.uid and g.uid=1

注意:

right … join … 以右表为主表 左表为辅表 会将主表数据 全都查询出来

十五、concat 字段连接

select concat(username,id) as newfield from user;

十六、数据库的导入和导出

(1) 导入

mysql -uroot -p 库名<恢复.sql

(2) 备份

mysqldump -uroot -p 库名>新名.sql

十七、对于创建新用户的操作

(1) 选择mysql库

user mysql

(2) 查询当前都有哪些用户

select user from user;

(3) 创建新用户

create user 新用户名 identified by ‘密码’;

(4) 赋予权限

grant all on 库名.* to 用户

grant all on online.* to zhangsan

update,select,delete …

(5) 回收权限

revoke all on 库名.* from 用户名

revoke all on online.* from zhangsan

(6) 删除用户

drop user zhangsan

(7) 刷新

flush privileges

十八、python操作MySQL

安装扩展库

pip install pymysql

import pymysql

(1) 链接 mysql数据库

db = pymysql.connect(‘主机’,用户名’,‘密码’,‘数据库’)

(2) 设置字符集

db.set_charset(‘utf8’)

(3) 创建游标对象(执行对数据的增删改查)

cursor = db.cursor()

(4) 准备SQL语句

sql = ‘’

(5) 执行SQL语句

cursor.execute(sql语句)

(6) 获取查询的结果集

cursor.fetchall()

cursor.fetchone()

(7) 获取受影响的行数

cursor.rowcount

(8) 关闭数据库链接

db.close()

注意:

pymysql 是开启事物的 所以执行除了查询以后的sql时 要执行 提交或者回滚

db.commit()

db.rollback()

最后:

如有不足或错误之处,还请各位读者指出,感谢各位!

发布了25 篇原创文章 · 获赞 5 · 访问量 1497

猜你喜欢

转载自blog.csdn.net/weixin_43656359/article/details/103723046