
MySQL从入门到进阶
发布于 2026年11月9日 18:54⏱ 2 分钟阅读👁 9
mysql 入门到进阶常用命令
第1章 mysql 基础入门
1.1 连接与基本操作
-- 连接mysql
mysql -u username -p
-- 查看所有数据库
show databases;
-- 创建数据库
create database database_name;
-- 使用数据库
use database_name;
-- 查看所有表
show tables;
-- 查看表结构
describe table_name;1.2 数据操作基础
-- 查询数据
select column1, column2 from table_name;
select * from table_name;
-- 根据条件查询
select * from table_name where condition;
select * from table_name where column1 = value;
-- 查询结果排序
select * from table_name order by column_name asc/desc;
-- 查询结果分页
select * from table_name limit 0, 10; -- 前10条
select * from table_name limit 10, 10; -- 第11-20条第2章 数据管理操作
2.1 插入数据
-- 插入单行数据
insert into table_name (col1, col2) values (value1, value2);
-- 插入多行数据
insert into table_name (col1, col2) values (value1, value2), (value3, value4);
-- 插入子查询数据
insert into table_name (col1, col2) select col1, col2 from other_table;2.2 更新数据
-- 更新单行数据
update table_name set col1 = value1 where condition;
-- 更新多行数据
update table_name set col1 = value1, col2 = value2 where condition;
-- 更新并返回受影响的行数
update table_name set col1 = value1 where condition;2.3 删除数据
-- 删除单行数据
delete from table_name where condition;
-- 删除多行数据
delete from table_name where condition1 or condition2;
-- 删除并返回受影响的行数
delete from table_name where condition;
-- 删除整个表
drop table table_name;第3章 表结构管理
3.1 创建表
-- 创建基本表
create table table_name (
id int primary key auto_increment,
name varchar(50) not null,
age int,
email varchar(100) unique,
created_at timestamp default current_timestamp
);
-- 创建带索引的表
create table table_name (
id int primary key,
name varchar(50),
index idx_name (name),
index idx_name_age (name, age)
);
-- 创建外键
create table child_table (
id int primary key,
parent_id int,
foreign key (parent_id) references parent_table(id)
);3.2 修改表结构
-- 添加列
alter table table_name add column new_column type;
-- 修改列
alter table table_name modify column column_name new_type;
-- 重命名列
alter table table_name change column old_name new_name type;
-- 删除列
alter table table_name drop column column_name;
-- 添加索引
alter table table_name add index idx_column (column_name);
-- 删除索引
alter table table_name drop index index_name;3.3 删除表
-- 删除表(如果存在)
drop table if exists table_name;
-- 删除多个表
drop table table1, table2, table3;第4章 高级查询技术
4.1 连接查询
-- 内连接
select t1.col1, t2.col2
from table1 t1
inner join table2 t2 on t1.id = t2.table1_id;
-- 外连接
select t1.col1, t2.col2
from table1 t1
left join table2 t2 on t1.id = t2.table1_id;
-- 自连接
select a.name as parent_name, b.name as child_name
from table1 a
join table1 b on a.id = b.parent_id;4.2 子查询
-- 标量子查询
select name, (select count(*) from orders where customer_id = c.id) as order_count
from customers c;
-- 相关子查询
select * from products p
where exists (select 1 from inventory i where i.product_id = p.id and i.stock > 0);
-- 子查询作为in条件
select * from customers where id in (select customer_id from orders where total > 1000);4.3 聚合函数
-- 基本聚合
select
count(*) as total_records,
sum(amount) as total_amount,
avg(price) as avg_price,
min(created_at) as earliest_date,
max(created_at) as latest_date
from table_name;
-- 分组聚合
select department, count(*) as employee_count, avg(salary) as avg_salary
from employees
group by department;
-- 分组过滤
select department, job_title, count(*) as count
from employees
group by department, job_title
having count(*) > 1;
-- 排序聚合
select department, job_title, count(*) as count
from employees
group by department, job_title
order by count(*) desc;4.4 联合查询
-- 内联合
select id, name, created_at from table1
union
select id, title, updated_at from table2;
-- 全联合
select id, name, created_at from table1
union all
select id, title, updated_at from table2;第5章 事务管理
5.1 基本事务
-- 开始事务
start transaction;
-- 事务操作
transaction_operation1;
transaction_operation2;
-- 提交事务
commit;
-- 回滚事务
rollback;5.2 保存点
start transaction;
-- 使用保存点
do_operation1;
savepoint sp1;
do_operation2;
-- 回滚到保存点
rollback to sp1;
do_operation3;
commit;第6章 索引与性能优化
6.1 索引管理
-- 创建唯一索引
create unique index idx_email on users(email);
-- 创建组合索引
create index idx_name_email on users(name, email);
-- 查看表索引
show index from table_name;
-- 删除索引
drop index index_name on table_name;6.2 优化查询
-- 使用适当的索引
-- 不要写这样的查询:select * from users where email = 'test@example.com';
-- 应该写:select * from users use index (idx_email) where email = 'test@example.com';
-- 避免全表扫描
-- 检查执行计划
explain select * from table_name where column_name = value;
-- 索引合并提示
select * from table_name force index (idx1, idx2) where col1 = value1 and col2 = value2;第7章 存储过程与函数
7.1 创建存储过程
-- 简单存储过程
delimiter $$
create procedure get_users_by_age(in min_age int, in max_age int)
begin
select * from users where age between min_age and max_age;
end $$
delimiter ;
-- 调用存储过程
call get_users_by_age(18, 25);7.2 创建函数
-- 创建标量函数
delimiter $$
create function get_full_name(first_name varchar(50), last_name varchar(50))
returns varchar(101)
deterministic
begin
return concat(first_name, ' ', last_name);
end $$
delimiter ;
-- 使用函数
select get_full_name(first_name, last_name) as full_name from users;第8章 视图管理
8.1 创建视图
-- 创建简单视图
create view active_users as
select * from users where status = 'active';
-- 创建计算视图
create view user_order_summary as
select
u.id,
u.name,
count(o.id) as total_orders,
sum(o.amount) as total_amount
from users u
left join orders o on u.id = o.user_id
group by u.id, u.name;8.2 更新视图
-- 更新视图数据
update active_users set status = 'verified' where last_login > date_sub(now(), interval 30 day);
-- 删除视图
drop view view_name;第9章 权限管理
9.1 权限控制
-- 查看权限
show grants for 'username'@'host';
-- 授予权限
grant select, insert, update, delete on database_name.* to 'username'@'host';
grant all privileges on database_name.* to 'username'@'host';
-- 撤销权限
revoke select, insert, update, delete on database_name.* from 'username'@'host';
-- 刷新权限
flush privileges;第10章 数据库维护
10.1 常规维护
-- 检查表状态
check table table_name;
-- 优化表
optimize table table_name;
-- 分析表
analyze table table_name;
-- 重建表
repair table table_name;10.2 日志管理
-- 查看错误日志
show errors;
-- 查看警告日志
show warnings;
-- 清空日志
reset master;第11章 事务日志与恢复
11.1 备份与恢复
-- 导出数据
mysqldump database_name > backup.sql;
-- 导入数据
mysql database_name < backup.sql;
-- 部分导出
mysqldump --tables table_name database_name > table_backup.sql;
-- 查看状态
show master status;
show slave status;第12章 性能分析
12.1 性能监控
-- 查看进程列表
show processlist;
-- 查看状态变量
show status;
-- 查看全局状态变量
show global status;
-- 查看变量
show variables;
-- 查看全局变量
show global variables;12.2 慢查询日志
-- 启用慢查询日志
set global slow_query_log = 'on';
set global long_query_time = 5;
-- 查看慢查询日志
show slow queries;
-- 修改慢查询日志文件位置
set global slow_query_log_file = '/path/to/slow_query.log';第13章 实用技巧
13.1 常用快捷命令
-- 显示当前数据库
database();
-- 显示服务器信息
select version(), current_user();
-- 获取最近插入的id
select last_insert_id();
-- 当前日期时间
select now(), curdate(), curtime();
-- 字符串操作
select length('hello'), upper('world'), lower('WORLD');
select substring('hello', 2, 3), concat('hello', ' ', 'world');
-- 日期时间操作
select date_add(now(), interval 7 day), datediff(now(), '2023-01-01');
select year(now()), month(now()), day(now());13.2 调试技巧
-- 查看查询计划
explain select * from table_name where column_name = value;
-- 执行查询并显示结果
explain format=tree select * from table_name where column_name = value;
-- 测试查询性能
set profiling = 1;
select * from table_name where column_name = value;
show profile;
show profile for query 1;第14章 常见问题排查
14.1 常见错误解决
-- 1692 未知的时区
set time_zone = '+08:00';
-- 1055 不同主机名
set global hostname = 'your_hostname';
-- 1146 来自服务器的未知表
show tables;
-- 1054 未知列名
describe table_name;14.2 性能问题
-- 查找慢查询
show slow queries;
-- 清空临时表
drop temporary table if exists temp_table_name;
-- 清空查询缓存
reset query cache;第15章 实战案例
15.1 电商网站常用模式
-- 商品浏览统计
create view product_view_stats as
select
date(created_at) as view_date,
product_id,
count(*) as view_count
from product_views
group by date(created_at), product_id;
-- 库存管理
create trigger update_stock after insert on order_items
for each row
begin
update products
set stock_quantity = stock_quantity - new.quantity
where id = new.product_id;
end $$
delimiter ;15.2 管理系统常用模式
-- 用户登录日志
create table login_logs (
id int primary key auto_increment,
user_id int,
login_time timestamp default current_timestamp,
ip_address varchar(45),
user_agent text
);
-- 系统错误日志
create table error_logs (
id int primary key auto_increment,
error_code varchar(20),
error_message text,
occurred_at timestamp default current_timestamp,
module varchar(50)
);附录:常用函数
字符串函数
concat()- 字符串拼接substring()- 字符串截取length()- 字符串长度upper()/lower()- 大小写转换
日期时间函数
now()- 当前日期时间date_add()/date_sub()- 日期加减datediff()- 日期差year()/month()/day()- 日期提取
数学函数
abs()- 绝对值round()- 四舍五入ceil()/floor()- 进位/取整rand()- 随机数
控制流函数
if()- 条件判断case- 多条件判断nullif()- 为NULL赋值
结束语
mysql是许多应用程序的基础,掌握这些常用命令将帮助你更高效地管理和操作数据库。请记住,在实际使用时要根据具体情况调整命令,并注意数据的安全性。日常开发中建议定期备份数据,并监控数据库的性能表现。
评论 (1)
匿匿名2026年11月10日 20:55
好用功