MySQL常用操作

用户管理

create user 'admin'@'192.168.1.%' identified by '123..com';         # 创建一个用户,设定允许登录的地址段
drop user 'admin'@'192.168.1.%';                                    # 删除用户
rename user 'admin'@'192.168.1.%' to 'admin1'@'%';                  # 修改用户信息
set password for 'admin1'@'%' = Password('123..com');               # 设置密码
注:用户权限信息是保存在mysql库中,所以也可以直接更改mysql表中的内容,但极力不推荐这么操作

权限管理

show grants for 'admin'@'%';                                        # 查看权限
grant select,insert,update on mysql.user to 'admin'@'192.168.1.%';  # 授权数据库权限
grant all privileges on mysql.user to 'admin'@'192.168.1.%';        # 授权数据库所有权限
revoke all privileges on mysql.user from 'admin'@'192.168.1.%';     # 取消权限
all privileges                      除grant外的所有权限
select                              仅查权限
select,insert                       查和插入权限
usage                               无访问权限
alter                               使用alter table
alter routine                       使用alter procedure和drop procedure
create                              使用create table
create routine                      使用create procedure
create temporary tables             使用create temporary tables
create user                         使用create user、drop user、rename user和revoke  all privileges
create view                         使用create view
delete                              使用delete
drop                                使用drop table
execute                             使用call和存储过程
file                                使用select into outfile 和 load data infile
grant option                        使用grant 和 revoke
index                               使用index
insert                              使用insert
lock tables                         使用lock table
process                             使用show full processlist
select                              使用select
show databases                      使用show databases
show view                           使用show view
update                              使用update
reload                              使用flush
shutdown                            使用mysqladmin shutdown(关闭MySQL)
super                               使用change master、kill、logs、purge、master和set global。还允许mysqladmin调试登陆
replication client                  服务器位置的访问
replication slave                   由复制从属使用
权限参数
数据库名.*          数据库中的所有
数据库名.表         指定数据库中的某张表
数据库名.存储过程   指定数据库中的存储过程
*.*                 所有数据库
数据库-表路径结构

操作数据库

show databases;                                 # 查看数据库
create database db1;                            # 创建数据库
create database db1 default charset utf8;       # 创建数据库,并设置字符集
drop database db1;                              # 删除数据库
use db1;                                        # 进入数据库

操作表

show tables;                                                        # 查看已创建的表
desc tablename;                                # 查看表结构
create table t1(id int(1),name char(4)); # 创建表 create table t1(id int(1) not null); # 创建表,设置非空字段 create table t1(id int(1) default 1); # 创建表,设置默认字段 create table t1(id int(1) auto_increment key); # 创建表,设置自增字段,自增字段必须和key同时使用 # auto_increment 表示自增,一个表中只能有一个自增列;对于自增可以设置步长和起始值 create table t1(id int(1) PRIMARY key); # 创建表,设置主键 # 主键的作用是用来约束(不能重复且不能为空),并且加速查找;一个表中只能有一个主键列;如果主键使用单个列,则它的值必须唯一,如果是多列,则其组合必须唯一。 create table t1(id int(1),name char(4)) default charset=utf8; # 创建表,并设置字符集 create table t1(id int(1),name char(4)) engine=innodb; # 创建表,并设置引擎 drop table t1; # 删除表 show create table t1; # 查看表的详细信息,可以加入G来进行美化

基本数据类型

    int[(m)] [unsigned] [zerofill]          整数,数据类型用于保存一些范围的整数数值范围;
    特别注意:整数类型中的m仅用于显示,对存储范围无限制。例如: int(5),当插入数据2时,select 时数据显示为: 00002
        有符号:-21474836482147483647
        无符号:04294967295

    tinyint[(m)] [unsigned] [zerofill]      小整数,数据类型用于保存一些范围的整数数值范围;特别注意:MySQL中无布尔值,使用tinyint(1)构造。
        有符号:-128127
        无符号:0255

    bit[(M)]            二进制位(101001),m表示二进制位的长度(1-64),默认m=1

    bigint[(m)] [unsigned] [zerofill]       大整数,数据类型用于保存一些范围的整数数值范围
        有符号:-92233720368547758089223372036854775807
        无符号:018446744073709551615

    decimal[(m[,d])] [unsigned] [zerofill]  准确的小数值,m是数字总个数(负号不算),d是小数点后个数。 m最大值为65,d最大值为30。
    特别注意:对于精确数值计算时需要用此类型,decaimal能够存储精确值的原因在于其内部按照字符串存储。

    FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]      单精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。数值越大,越不准确
        有符号:1.175494351E-38 to 3.402823466E+38
        无符号:-3.402823466E+38 to -1.175494351E-38

    DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]     双精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。数值越大,越不准确
        有符号:2.2250738585072014E-308 to 1.7976931348623157E+308
        无符号:-1.7976931348623157E+308 to -2.2250738585072014E-308

    char(m)             表示固定长度的字符串,可以包含最多达255个字符。其中m代表字符串的长度。即使数据小于m长度,也会占用m长度
    varchar(m)          用于变长的字符串,可以包含最多达255个字符。其中m代表该数据类型所允许保存的字符串的最大长度,只要长度小于该最大值的字符串都可以被保存在该数据类型中。虽然varchar使用起来较为灵活,但是从整个系统的性能角度来说,char数据类型的处理速度更快,有时甚至可以超出varchar处理速度的50%。因此,用户在设计数据库时应当综合考虑各方面的因素,以求达到最佳的平衡
    text                用于保存变长的大字符串,可以组多到65535 (2**161)个字符。
    mediumtext          A TEXT column with a maximum length of 16,777,215 (2**241) characters.
    longtext            A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**321) characters.
    enum                An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than 3000.)
    set                 A SET column can have a maximum of 64 distinct members.
    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 年某时)
    # 更多参考:https://www.runoob.com/mysql/mysql-data-types.html
View Code

操作表内容

插入操作
insert
into t1(id,name) values(1,'liangxiao');  # 插入数据 insert into t1(id,name) values(1,'梁晓');      # 插入中文内容 insert into t2(id,name) select id,name from t1;  # 将t1中的id与name导入到t2中
查询操作
select id from t1;                                                                    # 查看表内容----id
select id from t1 where id > 10 or name='alxe';                                       # 查找内容符合条件的项
select id as uid,name from t1;                                                        # 查找指定内容,并且更改列标题
select id,name,1 from t1;                                                             # 查找指定的内容,并且在指定内容后面添加常量项
select id from t1 where id in (1,2,3,4);                                              # 查找属于元组中的内容
select id from t1 where id not in (1,2,3,4);                                          # 查找不属于元组中的内容
select id from t1 where id in (select id from t2);                                    # 查找属于元组中的内容,这里只能用单列
select id from t1 where id between 1 and 200;                                         # 查找闭区间中的内容
select * from t1 where name like "alex%";                                             # 通配符查找,查看t1中name列中alex开头的内容,后面可以跟无穷多的内容
select * from t1 where name like "alex_";                                             # 通配符查找,查看t1中name列中alex开头的内容,后面只能跟一个单一字符
select * from t1 limit 5;                                                             # 查看前5行;
select * from t1 limit 4,5;                                                           # 查看从第4行开始往下的第5行;
select * from t1 limit 2 offset 2;                                                    # 查看从第2行开始查往下两行,包括第二行,跟上面功能是一样,但是位置参数功能刚好相反
select * from t1 order by id desc;                                                    # 根据指定列进行从大到小排序查看
select * from t1 order by id asc;                                                     # 根据指定列进行从小到大排序查看
select * from t1 order by id desc,uid desc;                                           # 多列排序查看
select num from t1 group by num;                                                      # 根据num进行分组去重,by后面的num是用来指定分区列,select后面的num是显示num的列;
select num,nid,count(*),sum(score),max(score),min(score) fromgroup by num,nid
# 特别注意:group by 必须在where之后,order by之前

select * from t1,t2 where t1.id = 1 and t2.name = '哈哈';                              # 连表查询
select A.num, A.name, B.name from A left join B on A.nid = B.nid;                     # 等效于上面的连表查询,之前的版本中这两个指令有性能上的差异,但是现在没有了;A表所有显示,如果B中无对应关系,则值为null
select A.num, A.name, B.name from A right join B on A.nid = B.nid;                    # 等效于上面的连表查询,之前的版本中这两个指令有性能上的差异,但是现在没有了;B表所有显示,如果B中无对应关系,则值为null
SELECT id FROM t1 UNION SELECT name FROM t2;                                          # 组合,自动处理重合
SELECT id FROM t1 UNION all SELECT name FROM t2;                                      # 组合,不自动处理重合
select sid from (select * from score where num > 60) as B;                 # 临时表查询
删除操作
delete from t1;                                                                     # 清空表,但是自增id
delete from t1 where id > 1 and name='alex';                                        # 清空表中符合条件的数据
truncate table t1;                                                                  # 清空表,并且清除自增id,比delete快
更新操作
update t1 set age=18;                                                                # 将表中age列中所有数据都改成18
update t1 set age=18,name='alex' where age=17;                                       # 将表中age列中等于17的数据都改成18
更改操作
alter table t10 AUTO_INCREMENT=20;                                                   # 修改下一个自增ID值
alter table 表名 add 列名 类型;                                                        # 添加列
alter table 表名 drop column 列名;                                                    # 删除列
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;                                      # 删除默认值
其他操作
show session variables like 'auto_inc%';                                            # 查看会话变量----自增函数相关内容
set session auto_increment_increment=2;                                             # 设置会话变量自增步长
set session auto_increment_offset=5;                                                # 设定会话变量自增长起始值,这个好像在innodb引擎中不会生效,下次需要注意一下
show global  variables like 'auto_inc%';                                            # 查看全局变量----自增函数相关内容
set global auto_increment_increment=2;                                              # 设置全局变量自增步长
set global auto_increment_offset=10;                                                # 设定全局变量自增长起始值,这个好像在innodb引擎中不会生效,下次需要注意一下
constraint fk_cc foreign key (color_id) references color(nid); # 创建外键,这部分内容是写在创建表的内容中
三目运算
select id,if(order_number=1111111113,'测试行3','测试行4' ) from td1 where order_number=1111111113;
# 首先用where匹配你想要的内容,然后三目运算根据你指定的内容再继续进行过滤
三目运算2
select id,CASE order_number=1111111113 WHEN 1 THEN '测试行3' else '测试行4' END as ORD from td1 where order_number=1111111113;
# 这里的关键字用到了CASE WHEN THEN ELSE END as,作用等效于第一个三目运算

基础实例

creat table color(
    nid int not null primary key,
    name char(16) not null
)

create table fruit(
    nid int not null primary key,
    smt char(32) null ,
    color_id int not null,
    constraint fk_cc foreign key (color_id) references color(nid)
    # 这里的fk_cc是外键名称,color_id是本表格中的外键列,color是被关联的表,nid是被关联的外键列
)
外键基础实例
CREATE TABLE t5 (
    nid int(11) NOT NULL AUTO_INCREMENT,
    pid int(11) not NULL,
    num int(11),
    primary key(nid,pid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

create table t6(
    id int auto_increment primary key,
    name char(10),
    id1 int,
    id2 int,
    CONSTRAINT fk_t5_t6 foreign key (id1,id2) REFERENCES t1(nid,pid)
)engine=innodb default charset=utf8;
外键主键组合实例
create table userinfo1(
    id int auto_increment primary key,
    name char(10),
    gender char(10),
    email varchar(64)
)engine=innodb default charset=utf8;

create table admin(
    id int not null auto_increment primary key,
    username varchar(64) not null,
    password VARCHAR(64) not null,
    user_id int not null,
    unique uq_u1 (user_id),
    CONSTRAINT fk_admin_u1 FOREIGN key (user_id) REFERENCES userinfo1(id)
)engine=innodb default charset=utf8;
外键唯一索引组合之一对一
create table userinfo2(
    id int auto_increment primary key,
    name char(10),
    gender char(10),
    email varchar(64)
)engine=innodb default charset=utf8;

create table host(
    id int auto_increment primary key,
    hostname char(64)
)engine=innodb default charset=utf8;

create table user2host(
    id int auto_increment primary key,
    userid int not null,
    hostid int not null,
    unique uq_user_host (userid,hostid),
    CONSTRAINT fk_u2h_user FOREIGN key (userid) REFERENCES userinfo2(id),
    CONSTRAINT fk_u2h_host FOREIGN key (hostid) REFERENCES host(id)
)engine=innodb default charset=utf8;
外键唯一索引组合之一对多

作业链接:http://www.cnblogs.com/wupeiqi/articles/5729934.html

参考链接:https://www.cnblogs.com/wupeiqi/articles/5713315.html

原文地址:https://www.cnblogs.com/guge-94/p/10813477.html