MySQL常用指令

一、连接与退出 MySQL

复制代码
-- 连接本地MySQL(默认端口3306)
mysql -u 用户名 -p

-- 连接远程MySQL
mysql -h 主机地址 -u 用户名 -p 端口号

-- 退出MySQL
exit; 或 quit;

二、数据库操作

复制代码
-- 查看所有数据库
show databases;

-- 创建数据库
create database 数据库名;

-- 创建数据库并指定字符集
create database 数据库名 character set utf8mb4;

-- 选择数据库
use 数据库名;

-- 删除数据库
drop database 数据库名;

-- 查看当前使用的数据库
select database();

三、数据表操作

复制代码
-- 查看当前数据库所有表
show tables;

-- 创建表
create table 表名 (
  字段1 数据类型 [约束],
  字段2 数据类型 [约束],
  ...
  primary key (主键字段)
);

-- 示例:创建用户表
create table users (
  id int auto_increment,
  name varchar(50) not null,
  age int,
  email varchar(100) unique,
  primary key (id)
);

-- 查看表结构
desc 表名; 或 describe 表名;

-- 修改表名
alter table 旧表名 rename to 新表名;

-- 添加字段
alter table 表名 add 字段名 数据类型 [约束];

-- 修改字段
alter table 表名 modify 字段名 新数据类型 [新约束];

-- 删除字段
alter table 表名 drop 字段名;

-- 删除表
drop table 表名;

四、数据操作(CRUD)

复制代码
-- 插入数据
insert into 表名 (字段1, 字段2, ...) values (值1, 值2, ...);

-- 示例
insert into users (name, age, email) values ('张三', 25, 'zhangsan@example.com');

-- 查询数据
select 字段1, 字段2 from 表名 [where 条件];

-- 查询所有字段
select * from 表名;

-- 带条件查询
select * from users where age > 18;

-- 排序查询
select * from users order by age desc; -- 降序
select * from users order by age asc;  -- 升序(默认)

-- 更新数据
update 表名 set 字段1=值1, 字段2=值2 where 条件;

-- 示例
update users set age=26 where name='张三';

-- 删除数据
delete from 表名 where 条件;

-- 示例
delete from users where id=1;

五、条件查询与高级操作

复制代码
-- 模糊查询
select * from users where name like '%张%';

-- 范围查询
select * from users where age between 18 and 30;

-- 聚合函数
select count(*) from users; -- 统计总数
select avg(age) from users; -- 平均值
select max(age) from users; -- 最大值
select min(age) from users; -- 最小值
select sum(age) from users; -- 总和

-- 分组查询
select age, count(*) from users group by age;

-- 分页查询(MySQL特有)
select * from users limit 10 offset 0; -- 从第0条开始,查询10条
select * from users limit 10; -- 简写,默认从0开始

六、索引操作

复制代码
-- 创建索引
create index 索引名 on 表名(字段名);

-- 查看表索引
show index from 表名;

-- 删除索引
drop index 索引名 on 表名;

七、用户与权限管理

复制代码
-- 创建用户
create user '用户名'@'主机地址' identified by '密码';

-- 授权(所有权限)
grant all privileges on 数据库名.* to '用户名'@'主机地址';

-- 刷新权限
flush privileges;

-- 查看用户权限
show grants for '用户名'@'主机地址';

-- 撤销权限
revoke 权限 on 数据库名.* from '用户名'@'主机地址';

-- 删除用户
drop user '用户名'@'主机地址';
相关推荐
正在走向自律11 分钟前
金仓数据库KingbaseES基础语法详解与实践指南
数据库·国产数据库·ddl·dml·kingbasees·sql语法·电科金仓
alonewolf_9912 分钟前
MySQL全局优化详解与8.0新特性全面解读
数据库·mysql
ASS-ASH14 分钟前
快速处理虚拟机磁盘扩容问题
linux·数据库·vmware·虚拟机·磁盘扩容
爱写bug的野原新之助20 分钟前
数据库及navicat工具
数据库·网络爬虫·工具
数据知道23 分钟前
一文掌握 MongoDB 存储引擎 WiredTiger 的原理
数据库·mongodb·数据库架构
Full Stack Developme28 分钟前
Mycat 2 实现 MySQL 读写分离,并且实现 主从同步
android·数据库·mysql
我是人✓31 分钟前
Spring IOC入门
java·数据库·spring
Hello.Reader32 分钟前
PyFlink DataStream 程序骨架、常用 Source/Sink、状态(State)、与 Table/SQL 互转一篇搞定
数据库·sql·linq
三不原则39 分钟前
故障案例:模型推理响应慢,排查 Redis 缓存集群问题
数据库·redis·缓存
alonewolf_9944 分钟前
MySQL Explain详解与索引优化实战
数据库·mysql·adb