MySql 基础 基本使用方法
安装MySQL
linux安装:阿里云服务器ecs配置之安装mysql
windows安装: 解压 管理员身份进cmd执行解压目录下的可执行文件 初始化 D:\mysql-8.0.12-winx64\mysql-8.0.12-winx64\bin\mysqld --initialize-insecure 运行服务端 D:\mysql-8.0.12-winx64\mysql-8.0.12-winx64\bin\mysqld 运行客户端 D:\mysql-8.0.12-winx64\mysql-8.0.12-winx64\bin\mysql -u root -p 安装windows服务: C:\Windows\system32>D:\mysql-8.0.12-winx64\mysql-8.0.12-winx64\bin\mysqld --install [--remove移除] 添加后可以在windows的服务里看到“MySQL”,管理员身份运行cmd,输入net start/stop MySQL即可启动
手动启动能成功,自启动的话,win10 下需要手动建data目录my.ini文件,不然无法启动服务;可能大家情况不一,请自行百度
数据库相关操作
创建数据库: create database 数据库名称 default charset utf8 collate utf8_general_ci; -- 设置默认编码 删除数据库: drop database 数据库名; drop database if exists 数据库名称; 查看数据库: show databases; 使用数据库: use db_name; -- 查看当前使用的数据库中所有表:SHOW TABLES; # select database(); # 查看当前使用的是哪个数据库 # 表示的是当前使用的是哪个数据库或者说会话登录到了哪个数据库中。
用户相关操作
-- ip 填 % 表示所有的ip地址都可登陆 create user '用户名'@'IP地址' identified by '密码'; -- 创建用户 drop user '用户名'@'IP地址'; -- 删除用户 rename user '用户名'@'IP地址' to '新用户名'@'IP地址'; -- 修改用户 set password for '用户名'@'IP地址' = Password('新密码'); -- 修改密码 为用户授权: select host,user from mysql.user; -- 查看用户 show grants for '用户'@'IP地址'; -- 查看权限 grant all privileges on db.t to 'username'@'ip';-- 授权 -- all privileges表示除授权权限外拥有所有的权限,也可填select,delete (查权限和删权限)等 -- db.t 表示对哪个数据库下的哪个表有此权限,填*.*意味着拥有所有数据库下的所有表的权限 -- 'username'@'ip' 用户只能在该IP下才能访问 # flush privileges 将数据读取到内存中,从而立即生效。 取消授权:revoke update,delete on db.t1 from 'username'@'ip'; 如果忘记密码: # 启动免授权服务端 mysqld --skip-grant-tables # 客户端 mysql -u root -p # 修改用户名密码 update mysql.user set authentication_string=password('666') where user='root'; flush privileges;
# 远程数据库
# mysql -h 192.168.3.233 -P 3306 -u root -p 123123
数据库表相关操作
创建表: create table t1( -- 列名 类型 是否可以为空, id int auto_increment primary key, -- auto_increment 自增:如果为某列设置自增列,插入数据时无需设置此列,默认将自增(表中只能有一个自增列) -- primary key 主键,不能为空 nid int not null defalut 2, -- 默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值 name char(10) )engine=innodb default charset=utf8; -- 引擎、默认字符 主键:一种特殊的唯一索引,,如果主键使用单个列,则它的值必须唯一,如果是多列,则其组合必须唯一。 create table tb1( nid int not null, num int not null, primary key(nid,num) ) 外键: create table fruit( id int not null primary key, fk_id int not null, constraint fk_tb1 foreign key (fk_id) references tb1(nid) ) 删除表: drop table 表名; drop table if exists 表名; 清空表: delete from 表名; -- 自增的id不重置 truncate table 表名; -- 自增的id重置 修改表: 添加列:alter table 表名 add 列名 类型; 删除列:alter table 表名 drop column 列名;
已存在表给其字段设置默认值 alter table word_nihongo alter column is_del set default 0;
删除not null alter table word_nihongo modify is_del char(1); 修改列: alter table 表名 modify column 列名 类型; -- 类型 alter table 表名 change 原列名 新列名 类型; -- 列名,类型 添加主键: alter table 表名 add primary key(列名); 删除主键: alter table 表名 drop primary key; alter table 表名 modify 列名 int, drop primary key; 添加外键:alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段); 删除外键:alter table 表名 drop foreign key 外键名称 修改默认值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000; 删除默认值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT; desc tabl_name; -- 显示表结构,字段类型,主键,是否为空等属性,但不显示外键。 show create table table_name; -- 该命令把创建表的DDL显示出来,于是表结构、类型,外键,备注全部显示出来了。
索引:
# 创建表时 create table in1( nid int not null auto_increment primary key, -- 主键索引,两个功能:加速查询 和 唯一约束(不可含null) name varchar(32) not null, addr varchar(32) not null -- index ix_name (name) -- 普通索引,仅有一个功能:加速查询 -- unique ix_name (name) -- 唯一索引,有两个功能:加速查询 和 唯一约束(可含null) -- primary key(nid) -- 也可在此创建主键索引 -- index ix_name_addr (name(10),addr(5)) -- 组合索引 ) # 表已创建 create index index_name on table_name(column_name);-- 创建普通索引 drop index index_name on table_name; -- 删除普通索引 alter table 表名 add primary key(列名); -- 创建主键 alter table 表名 drop primary key; -- 删除主键 alter table 表名 modify 列名 int, drop primary key; -- 删除主键 create unique index 索引名 on 表名(列名); -- 创建唯一索引 drop unique index 索引名 on 表名; -- 删除唯一索引 create index 索引名 on 表名(列名1,列名2); -- 创建组合索引 组合索引最左前缀,如果组合索引为:(name,email) name and email -- 使用索引 name -- 使用索引 email -- 不使用索引 show index from table_name; -- 查看索引 不会使用索引的情况: -- like '%xx' select * from tb1 where name like '%xx'; -- 使用函数 select * from tb1 where reverse(name) = 'xx'; -- or -- 当or条件中有未建立索引的列才失效 select * from tb1 where nid = 1 or age = 18; -- != -- 如果是主键,则还是会走索引 select * from tb1 where name != 'xx' -- > -- 如果是主键或索引是整数类型,则还是会走索引 select * from tb1 where name > 'alex' -- order by -- 如果对主键排序,则还是走索引 select email from tb1 order by name desc; -- 当根据索引排序时候,选择的映射如果不是索引,则不走索引 -- 组合索引最左前缀 如果组合索引为:(name,email) name and email -- 使用索引 name -- 使用索引 email -- 不使用索引
字段:
bit[(M)] 二进制位(101001),m表示二进制位的长度(1-64),默认m=1 tinyint[(m)] [unsigned] [zerofill] 小整数,数据类型用于保存一些范围的整数数值范围: 有符号: -128 ~ 127. 无符号: ~ 255 特别的: MySQL中无布尔值,使用tinyint(1)构造。 int[(m)][unsigned][zerofill] 整数,数据类型用于保存一些范围的整数数值范围: 有符号: -2147483648 ~ 2147483647 无符号: ~ 4294967295 特别的:整数类型中的m仅用于显示,对存储范围无限制。例如: int(5),当插入数据2时,select 时数据显示为: 00002 bigint[(m)][unsigned][zerofill] 大整数,数据类型用于保存一些范围的整数数值范围: 有符号: -9223372036854775808 ~ 9223372036854775807 无符号: ~ 18446744073709551615 decimal[(m[,d])] [unsigned] [zerofill] 准确的小数值,m是数字总个数(负号不算),d是小数点后个数。 m最大值为65,d最大值为30。 特别的:对于精确数值计算时需要用此类型 decaimal能够存储精确值的原因在于其内部按照字符串存储。 FLOAT[(M,D)] [UNSIGNED] [ZEROFILL] 单精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。 无符号: -3.402823466E+38 to -1.175494351E-38, 1.175494351E-38 to 3.402823466E+38 有符号: 1.175494351E-38 to 3.402823466E+38 **** 数值越大,越不准确 **** DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL] 双精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。 无符号: -1.7976931348623157E+308 to -2.2250738585072014E-308 2.2250738585072014E-308 to 1.7976931348623157E+308 有符号: 2.2250738585072014E-308 to 1.7976931348623157E+308 **** 数值越大,越不准确 **** char (m) char数据类型用于表示固定长度的字符串,可以包含最多达255个字符。其中m代表字符串的长度。 PS: 即使数据小于m长度,也会占用m长度 varchar(m) varchars数据类型用于变长的字符串,可以包含最多达255个字符。其中m代表该数据类型所允许保存的字符串的最大长度,只要长度小于该最大值的字符串都可以被保存在该数据类型中。 注:虽然varchar使用起来较为灵活,但是从整个系统的性能角度来说,char数据类型的处理速度更快,有时甚至可以超出varchar处理速度的50%。因此,用户在设计数据库时应当综合考虑各方面的因素,以求达到最佳的平衡 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. enum 枚举类型, An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than 3000.) 示例: CREATE TABLE shirts ( name VARCHAR(40), size ENUM('x-small', 'small', 'medium', 'large', 'x-large') ); INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),('polo shirt','small'); set 集合类型 A SET column can have a maximum of 64 distinct members. 示例: CREATE TABLE myset (col SET('a', 'b', 'c', 'd')); INSERT INTO myset (col) VALUES ('a,d'), ('d,a'), ('a,d,a'), ('a,d,d'), ('d,a,d'); DATE YYYY-MM-DD(1000-01-01/9999-12-31) TIME HH:MM:SS('-838:59:59'/'838:59:59') YEAR YYYY(1901/2155) DATETIME YYYY-MM-DD HH:MM:SS(1000-01-01 00:00:00/9999-12-31 23:59:59 Y) TIMESTAMP YYYYMMDD HHMMSS(1970-01-01 00:00:00/2037 年某时)
操作数据库表的内容
# 补:=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- # 查询时格式化时间 mysql> select date_format(create_time,'%Y-%m') from blog_article;
# MYSQL避免批量插入重复数据报错的解决方案
insert ignore into ip_pool(proxy) values (666); # 只警告,跳过继续执行sql
replace into ip_pool(proxy) values (666); # 更新,自增id会变
# 创建自动生成时间的列 和 修改时自动更新时间的列
CREATE TABLE temp (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(10),
created timestamp null DEFAULT CURRENT_TIMESTAMP,
updated timestamp null DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO temp (id, name);
# 插入数据时,自动填写创建时间和更新时间,修改时更新updated列的时间,created的不变 增: insert into 表名(列名,列名2) value(列1值,列2值); insert into 表 (列名,列名...) select (列名,列名...) from 表;
补充:insert into 表 values(列1值,列2值),(列1值,列2值),(列1值,列2值);
-- 主键自增,第一列在增加数据的时候,可以写为0或者null,这样添加数据可以自增, 从而可以添加全部数据,而不用特意规定那几列添加数据。
删: delete from 表; delete from 表 where id = 1 and name = 'xx'; 改: update 表 set name = 'xx' where id > 1; 查:
# 补:=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
select count(*) from table_name; -- 查询表中有多少条数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
select * from 表; select * from 表 where id > 1; select nid,name,gender as gg from 表 where id > 1; 条件: select * from 表 where id > 1 and name != 'xx' and num = 12; select * from 表 where id between 5 and 16; select * from 表 where id in (11,22,33); select * from 表 where id not in (11,22,33); select * from 表 where id in (select nid from 表); 通配符: select * from 表 where name like 'a%'; -- 匹配a开头的字符串 -- %匹配所有字符 select * from 表 where name like 'a_'; -- _匹配以a开头和一个其他字符的字符串 -- _一个占位符 分页: select * from 表 limit 5; -- 前5行 select * from 表 limit 4,5; -- 从第4行开始的5行 select * from 表 limit 5 offset 4; -- 从第4行开始的5行 排序: select * from 表 order by 列 asc; -- 根据 “列” 从小到大排列 select * from 表 order by 列 desc; -- 根据 “列” 从大到小排列 select * from 表 order by 列1 desc,列2 asc; -- 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序 分组: select num from 表 group by num; select num,nid from 表 group by num,nid; select num,nid from 表 where nid > 10 group by num,nid order by nid desc; select num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nid; select num from 表 group by num having max(id) > 10; 注:group by 必须在where之后,order by之前,having对分组后的数据做筛选 临时表: SELECT * FROM ( SELECT age, NAME FROM tb1 WHERE nid > 2 ) AS A WHERE A. age > 'xx'; 连表: select A.num, A.name, B.name from A,B Where A.nid = B.nid; -- 无对应关系则不显示 select A.num, A.name, B.name from A -- inner join B -- 内连接,无对应关系则不显示 -- left join B -- 左连接,以左表为准,右表无值为null -- right join B -- 右连接,以右表为准,左表无值为null on A.nid = B.nid; -- 按哪个字段连表 组合,将数据揉到一起: select nickname from A union -- 自动处理重合 union all -- 不处理重合 select name from B
备份
全量备份(数据+结构): #mysqldump -uroot -pmima -A > 备份文件路径 指定库备份(数据+洁构): #mysqldump -uroot -p密码 库名 > 备份文件路径 多个库备份(数据+结构): #mysqldump -uroot -p123456 --databases dbl db2 > 备份文件路径 备份数据库某个(些)表: #mysqldump -uroot -p123456 db table1 table2 > 备份文件路径
还原
还原部分(1) mysql命令行source方法和(2)系统命令行方法 1、还原全部数据库: (1) mysql命令行: mysql> source 备份交件路径 (2) 系统命令行: #mysql -uroot -p123456 < 备份文件路径 2、还原单个数据库(需指定数据库) (1) mysql> use 库名 mysql> source 备份文件路径 (2) mysql -uroot -p123456 库名 < 备份文件路径
视图
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
视图是一个虚拟表(非真实存在),可将其当作表来使用。应用:多次查询某个复杂查询的结果集 创建视图: --格式:CREATE VIEW 视图名称 AS SQL语句 CREATE VIEW v1 AS SELET nid, name FROM A WHERE nid > 4 删除视图: --格式:DROP VIEW 视图名称 DROP VIEW v1; 修改视图: -- 格式:ALTER VIEW 视图名称 AS SQL语句 ALTER VIEW v1 AS SELET A.nid, B. NAME FROM A LEFT JOIN B ON A.id = B.nid LEFT JOIN C ON A.id = C.nid WHERE A.id > 2 AND C.nid < 5 使用视图: 使用视图时,将其当作表进行操作即可,由于视图是虚拟表,所以无法使用其对真实表进行创建、更新和删除操作,仅能做查询用。 select * from v1
事务
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
事务 # 事务用来管理insert,update,delete语句 # 使用Innodb数据库引擎,保证SQL语句要么全部执行,要么全部不执行,要么成功,要么撤回。 # 事务是必须满足4个条件: 1、事务的原子性:一组事务,要么成功;要么撤回。 2、稳定性: 有非法数据(外键约束之类),事务撤回。 3、隔离性:事务独立运行。一个事务处理后的结果,影响了其他事务,那么其他事务会撤回。事务的100%隔离,需要牺牲速度。 4、可靠性:软、硬件崩溃后,InnoDB数据表驱动会利用日志文件重构修改。 # 在Mysql控制台使用事务来操作 mysql> begin; # 开始一个事务 mysql> insert into a(age) values(18); mysql> rollback; # 回滚,这样数据是不会写入的 mysql> commit; # 如果数据没问题,输入commit提交命令