当前位置: 代码网 > it编程>数据库>Mysql > MySQL常用SQL语句和使用场景代码示例

MySQL常用SQL语句和使用场景代码示例

2026年04月27日 Mysql 我要评论
1. 数据库操作创建数据库create database mydb character set utf8mb4 collate utf8mb4_unicode_ci;查看所有数据库show datab

1. 数据库操作

创建数据库

create database mydb character set utf8mb4 collate utf8mb4_unicode_ci;

查看所有数据库

show databases;

选择数据库

use mydb;

删除数据库

drop database mydb;

修改数据库

alter database mydb character set utf8mb4;

2. 表操作

创建表

create table users (
    id int auto_increment primary key,
    username varchar(50) not null unique,
    email varchar(100) not null,
    password varchar(255) not null,
    age int default 18,
    status tinyint default 1 comment '1:active 0:inactive',
    created_at timestamp default current_timestamp,
    updated_at timestamp default current_timestamp on update current_timestamp
) engine=innodb default charset=utf8mb4;

查看表结构

desc users;
-- 或
describe users;
-- 或
show columns from users;

查看所有表

show tables;

修改表结构

-- 添加列
alter table users add column phone varchar(20);
​
-- 删除列
alter table users drop column phone;
​
-- 修改列类型
alter table users modify column username varchar(100);
​
-- 重命名列
alter table users change column username user_name varchar(50);
​
-- 添加索引
alter table users add index idx_email (email);
​
-- 添加外键
alter table orders add constraint fk_user_id
    foreign key (user_id) references users(id);

删除表

drop table users;
-- 或
drop table if exists users;

清空表(保留表结构)

truncate table users;

重命名表

rename table old_name to new_name;

3. 数据操作 (crud)

插入数据 (insert)

-- 插入单条记录
insert into users (username, email, password) values ('zhangsan', 'zhangsan@example.com', '123456');
​
-- 插入多条记录
insert into users (username, email, password) values
    ('lisi', 'lisi@example.com', '123456'),
    ('wangwu', 'wangwu@example.com', '123456');
​
-- 从另一表插入数据
insert into users_backup select * from users;

更新数据 (update)

-- 更新单个字段
update users set email = 'newemail@example.com' where id = 1;
​
-- 更新多个字段
update users set email = 'new@example.com', status = 0 where id = 1;
​
-- 批量更新
update users set status = 0 where age < 18;

删除数据 (delete)

-- 删除指定记录
delete from users where id = 1;
​
-- 批量删除
delete from users where status = 0;
​
-- 清空表(delete方式,会重置自增id)
delete from users;

4. 查询语句

基本查询

-- 查询所有列
select * from users;
​
-- 查询指定列
select id, username, email from users;
​
-- 去重查询
select distinct status from users;

条件查询 (where)

-- 等于
select * from users where id = 1;
​
-- 不等于
select * from users where status != 0;
​
-- 多条件 and
select * from users where age >= 18 and age <= 60;
​
-- 多条件 or
select * from users where age < 18 or age > 60;
​
-- in 查询
select * from users where id in (1, 2, 3);
​
-- not in 查询
select * from users where id not in (1, 2, 3);
​
-- between 范围查询
select * from users where age between 18 and 60;
​
-- like 模糊查询
select * from users where username like 'zhang%';  -- 以zhang开头
select * from users where username like '%san';     -- 以san结尾
select * from users where username like '%an%';     -- 包含an
select * from users where username like 'zh_ng';    -- _匹配单个字符
​
-- is null 查询
select * from users where phone is null;
​
-- is not null 查询
select * from users where phone is not null;

排序 (order by)

-- 升序
select * from users order by age asc;
​
-- 降序
select * from users order by created_at desc;
​
-- 多字段排序
select * from users order by status asc, age desc;

限制结果集 (limit)

-- 查询前n条
select * from users limit 10;
​
-- 分页查询(跳过m条,取n条)
select * from users limit 0, 10;   -- 第1页,每页10条
select * from users limit 10, 10;  -- 第2页,每页10条

分组查询 (group by)

-- 按状态分组统计
select status, count(*) as count from users group by status;
​
-- 多字段分组
select status, age, count(*) as count from users group by status, age;
​
-- 分组后过滤(having)
select status, count(*) as count from users
group by status
having count > 5;

5. 聚合函数

-- count 统计数量
select count(*) from users;
select count(distinct email) from users;

-- sum 求和
select sum(amount) from orders;

-- avg 平均值
select avg(age) from users;

-- max 最大值
select max(price) from products;

-- min 最小值
select min(price) from products;

-- 组合使用
select
    count(*) as total,
    avg(age) as avg_age,
    max(age) as max_age,
    min(age) as min_age
from users;

6. 连接查询

内连接 (inner join)

-- 只返回匹配的记录
select u.username, o.order_no, o.amount
from users u
inner join orders o on u.id = o.user_id;

左连接 (left join)

-- 返回左表所有记录,右表没有匹配则为null
select u.username, o.order_no
from users u
left join orders o on u.id = o.user_id;

右连接 (right join)

-- 返回右表所有记录,左表没有匹配则为null
select u.username, o.order_no
from users u
right join orders o on u.id = o.user_id;

多表连接

select u.username, o.order_no, p.product_name
from users u
inner join orders o on u.id = o.user_id
inner join order_items oi on o.id = oi.order_id
inner join products p on oi.product_id = p.id;

7. 索引操作

创建索引

-- 普通索引
create index idx_username on users(username);

-- 唯一索引
create unique index idx_email on users(email);

-- 组合索引
create index idx_status_age on users(status, age);

-- 全文索引
create fulltext index idx_content on articles(content);

查看索引

show index from users;

删除索引

drop index idx_username on users;

8. 视图操作

创建视图

create view user_orders as
select u.id, u.username, count(o.id) as order_count
from users u
left join orders o on u.id = o.user_id
group by u.id, u.username;

查看视图

select * from user_orders;

删除视图

drop view user_orders;

9. 事务处理

-- 开启事务
start transaction;
-- 或
begin;

-- 执行sql
update users set balance = balance - 100 where id = 1;
update users set balance = balance + 100 where id = 2;

-- 提交事务
commit;

-- 回滚事务
rollback;

10. 用户权限管理

创建用户

create user 'testuser'@'localhost' identified by 'password123';
create user 'testuser'@'%' identified by 'password123';  -- 允许远程连接

授权

-- 授予所有权限
grant all privileges on mydb.* to 'testuser'@'localhost';

-- 授予特定权限
grant select, insert, update on mydb.* to 'testuser'@'localhost';

-- 刷新权限
flush privileges;

查看权限

show grants for 'testuser'@'localhost';

撤销权限

revoke all privileges on mydb.* from 'testuser'@'localhost';

删除用户

drop user 'testuser'@'localhost';

修改密码

alter user 'testuser'@'localhost' identified by 'newpassword';

11. 常用场景示例

场景1:用户注册与登录

-- 注册(插入用户)
insert into users (username, email, password) values ('newuser', 'user@example.com', md5('password'));

-- 登录验证
select * from users where username = 'newuser' and password = md5('password');

场景2:数据分页查询

-- 通用分页公式:limit (page-1)*pagesize, pagesize
select * from users order by created_at desc limit 0, 10;   -- 第1页
select * from users order by created_at desc limit 10, 10;  -- 第2页

场景3:数据统计报表

-- 每日新增用户统计
select date(created_at) as date, count(*) as new_users
from users
group by date(created_at)
order by date desc;

-- 各状态用户数量
select
    case status
        when 1 then '活跃'
        when 0 then '禁用'
        else '未知'
    end as status_name,
    count(*) as count
from users
group by status;

场景4:排行榜

-- 用户消费排行top10
select u.username, sum(o.amount) as total_amount
from users u
inner join orders o on u.id = o.user_id
group by u.id, u.username
order by total_amount desc
limit 10;

场景5:查找重复数据

-- 查找重复的邮箱
select email, count(*) as count
from users
group by email
having count(*) > 1;

-- 删除重复数据(保留id最小的)
delete u1 from users u1
inner join users u2
where u1.id > u2.id and u1.email = u2.email;

场景6:数据导入导出

-- 导出数据到csv文件(命令行)
mysql -u root -p -e "select * from users" mydb > users.csv;

-- 导入csv文件
load data infile '/path/to/users.csv'
into table users
fields terminated by ','
enclosed by '"'
lines terminated by '\n';

场景7:批量更新

-- case when 批量更新
update users
set status = case
    when age < 18 then 0
    when age >= 18 and age < 60 then 1
    else 2
end;

场景8:时间范围查询

-- 查询最近7天的数据
select * from orders
where created_at >= date_sub(now(), interval 7 day);

-- 查询本月数据
select * from orders
where year(created_at) = year(now())
and month(created_at) = month(now());

-- 查询指定时间段
select * from orders
where created_at between '2024-01-01' and '2024-12-31';

场景9:树形结构查询(分类)

-- 假设categories表有id, name, parent_id字段
-- 查找某分类的所有子分类(递归,mysql 8.0+)
with recursive category_tree as (
    select * from categories where id = 1
    union all
    select c.* from categories c
    inner join category_tree ct on c.parent_id = ct.id
)
select * from category_tree;

场景10:软删除与恢复

-- 软删除(添加is_deleted字段)
update users set is_deleted = 1, deleted_at = now() where id = 1;
-- 查询未删除的数据
select * from users where is_deleted = 0;
-- 恢复数据
update users set is_deleted = 0, deleted_at = null where id = 1;

常用函数速查

字符串函数

concat(str1, str2)      -- 连接字符串
length(str)             -- 字符串长度
upper(str)              -- 转大写
lower(str)              -- 转小写
trim(str)               -- 去除首尾空格
substring(str, pos, len) -- 截取子串
replace(str, old, new)  -- 替换

日期时间函数

now()                   -- 当前日期时间
curdate()               -- 当前日期
curtime()               -- 当前时间
date(datetime)          -- 提取日期部分
year(date)              -- 提取年份
month(date)             -- 提取月份
day(date)               -- 提提取日
date_format(date, format) -- 日期格式化
date_add(date, interval expr unit) -- 日期增加
date_sub(date, interval expr unit) -- 日期减少

数值函数

abs(num)                -- 绝对值
round(num, decimals)    -- 四舍五入
ceil(num)               -- 向上取整
floor(num)              -- 向下取整
rand()                  -- 随机数

性能优化建议

  • 使用索引:为经常查询的where、join、order by字段添加索引

  • 避免 select *:只查询需要的字段

  • 合理使用 limit:限制返回结果数量

  • 避免在where中使用函数:会导致索引失效

  • 使用 explain:分析查询执行计划

  • 优化表结构:选择合适的数据类型

  • 分页优化:大数据量分页使用子查询或游标

  • 批量操作:使用批量插入代替单条插入

总结 

到此这篇关于mysql常用sql语句和使用场景的文章就介绍到这了,更多相关mysql常用sql语句使用场景内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com