一、用户管理
- 创建用户
CREATE USER 'username'@'host' IDENTIFIED BY 'password';
//username:要创建的用户名;
//host:指定该用户在哪个主机上可以登陆,如果是本地用户可用localhost,如果想让该用户可以从任意远程主机登陆,可以使用通配符%
//password:该用户的登陆密码,密码可以为空。
//例子:
CREATE USER 'Jerry'@'localhost' IDENTIFIED BY '123456';
CREATE USER 'Jerry'@'192.168.1.101_' IDENDIFIED BY '123456';
CREATE USER 'Jerry'@'%' IDENTIFIED BY '123456';
CREATE USER 'Jerry'@'%' IDENTIFIED BY '';
CREATE USER 'Jerry'@'%';
- 授权
//privileges:用户的操作权限,如SELECT,INSERT,UPDATE等,如果要授予所的权限则使用ALL
//databasename:数据库名
//tablename:表名,如果要授予该用户对所有数据库和表的相应操作权限则可用*表示,如*.*
GRANT privileges ON databasename.tablename TO 'username'@'host';
//例子:
GRANT SELECT, INSERT ON test.user TO 'Jerry'@'%';
GRANT ALL ON *.* TO 'Jerry'@'%';
GRANT ALL ON maindataplus.* TO 'Jerry'@'%';
3.设置与更改用户密码
SET PASSWORD FOR 'username'@'host' = PASSWORD('newpassword');
//如果是当前登陆用户用:
SET PASSWORD = PASSWORD("newpassword");
//例子:
SET PASSWORD FOR 'Jerry'@'%' = PASSWORD("123456");
- 删除用户
DROP USER 'username'@'host';
- 查看所有用户
SELECT User, Host FROM mysql.user;
二、字符集
- 查看字符集
show character set;
- 查看字符集的校对规则
show collation;
- 查看当前数据库的字符集
show variables like 'character%';
- 设置数据库字符集
alter database DATABASE_NAME character set utf8;
三、表操作:
- 查看表结构
desc tablename;
- 插入一列
//在最后追加一列
alter table users add column NEW_COLUMN_NAME varchar(20) not null;
//在最后追加一列,并设置默认值
alter table users add column NEW_COLUMN_NAME varchar(20) not null default '';
//在最前面插入一列
alter table users add column NEW_COLUMN_NAME varchar(20) not null first;
//插入到某一列之后
alter table users add column NEW_COLUMN_NAME varchar(20) not null after tel;
- 删除一列
alter table users drop column NEW_COLUMN_NAME;
- 添加主键
//主键的作用是保证数据的唯一性和完整性,同时通过主键检索表能够增加检索速度。
alter table users add primary key(uid);
- 删除主键
alter table users drop primary key;
四、内容操作:
- 条件判断where
//查询 uid 大于 1 的所有数据
select * from users where uid > 1;
//查询 uid 在 4 和 8 之间的所有数据,包含 4 和 8
select * from users where uid between 4 and 8;
//查询 uid 等于 1,3,5 的数据
select * from users where uid in (1,3,5);
//查询 uid 不等于 1,3,5 的所有数据
select * from users where uid not in (1,3,5);
- 排序 asc,desc
//升序
select * from users order by uid asc;
//降序
select * from users order by uid desc;
- 限制 limit
//查询前5行
select * from users limit 5;
//从第4行之后的5行
select * from users limit 4,5;
//从第五行之后的4行
select * from users limit 4 offset 5;
- 模糊查询 like
//nickname以a开头的所有数据
select * from users where nickname like 'a%';
//nickname包含a的所有数据
select * from users where nickname like '%a%';
- 多表联合查询
//查询users表uid=1的sex字段和game表uid=1的level字段
select sex,level from users,game where users.uid = 1 and game.uid = 1;
五、MySql用户手册:
环境:
MySQL:8.0.25
Windows10,企业版