MySQL数据库常用语句

修改数据表字符集编码

alter table 表名 convert to character set utf8mb4 collate utf8mb4_general_ci;

刷新权限

flush privileges;

创建新用户

create user '用户名'@'%' identified by '密码';
-- '%' 所有情况都能访问
-- 'localhost' 本机才能访问
-- '111.222.33.44' - 指定 ip 才能访问

新增用户、指定数据库、授权限

grant 权限列表 on `数据库名`.`表名` to '用户名'@'主机' identified by '密码' with grant option;
-- 举例:
# 用户test密码java可对website库下的所有表执行所有权限
grant all privileges on `website`.* to 'test'@'%' identified by 'java';
-- all 可以替换为 select, delete, update, create, drop
grant insert, select, update on `test_db`.`test_tbl` to 'someone'@'localhost' identified by '123456';

修改用户密码

update mysql.user set password = '新密码' where user = '用户名';

设置新的root 密码

update mysql.user set authentication_string = password("新密码") where user ='root' and host = 'localhost'

查看某个用户的权限

show grants for '用户名'@'主机';

删除用户

delete from mysql.user Where user = '用户名';

查看mysql所有用户

select user, host from mysql.user;

创建数据库 (指定编码格式)

create database `库名` default charset utf8mb4 collate utf8mb4_general_ci;

查看数据库版本

select version();

查看表字段

show full columns from `表名`;
-- 举栗:
show full columns from website_user;
describe `表名`;
-- 举栗:
describe website_user;

根据字段找库名和表名

select table_schema, table_name from information_schema.columns where column_name = '字段名';

根据表名查询字段的名称、类型、长度、注释

select column_name, data_type, character_maximum_length, is_nullable, column_comment 
from information_schema.columns where table_name = '表名';

根据注释查询字段

select column_name, column_comment,
from information_schema.columns
where table_name = '表名'
and table_schema = '数据库名'
and column_comment like '%需查询的注释%'

指定的字段后面追加字段

格式 : alter table 表名 add 新增的字段名 字段类型  是否为null(可选) comment '新字段的注释' after 表中要跟随的字段名
-- 举栗:
alter table user_info add nick_name varchar(10) not null comment '昵称' after username;
解析 : 
user_info 指表名; 
nick_name 指新增的字段名; 
varchar(10) 指新增字段的类型和长度; 
not null 指新增的字段不能为空; 
'昵称' 指注释; 
username 指表中原有的字段;

执行该SQL, user_info表中, username 字段后新增一个类型为 varchar 长度为10 且不为空 注释是昵称的字段 nick_name

问题

You can't specify target table 'result' for update in FROM clause

同一语句中不能先select出同一表中的某些值,再update这个表.

举栗:删除 table_a 表中姓名重复的数据
🟥反例

delete from table_a where name in (
	select name from table_a group by name having  count(name) > 1
)

[正确写法] 把结果集当作一个表,自我查询一遍

🟩正例

delete from table_a where name in (
	select name from (
		select name from table_a group by name having  count(name) > 1
	) as t1
)

ps:如有错误,欢迎批评指正,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

leeindex

感谢您的鼓励~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值