it编程 > 数据库 > Mysql

MySQL基础增删查改操作详解

8人参与 2026-01-31 Mysql

以下是 mysql 数据库基础的增删查改(crud)操作详解:

一、数据库操作

  1. 创建数据库
create database db_name;
create database if not exists db_name;  -- 不存在时才创建
create database db_name character set utf8mb4 collate utf8mb4_unicode_ci;
  1. 删除数据库
drop database db_name;
drop database if exists db_name;  -- 存在时才删除
  1. 选择/切换数据库
use db_name;

二、数据表操作

  1. 创建表
create table users (
    id int primary key auto_increment,        -- 主键,自增
    username varchar(50) not null unique,     -- 非空,唯一
    password varchar(255) not null,
    email varchar(100),
    age int default 18,                       -- 默认值
    created_at timestamp default current_timestamp,
    updated_at timestamp default current_timestamp on update current_timestamp
);
  1. 删除表
drop table table_name;
drop table if exists table_name;
  1. 修改表结构
-- 添加列
alter table users add column phone varchar(20);
-- 修改列
alter table users modify column email varchar(150);
-- 重命名列
alter table users change column phone mobile varchar(20);
-- 删除列
alter table users drop column mobile;
-- 添加索引
create index idx_username on users(username);
-- 删除索引
drop index idx_username on users;

三、数据操作(crud)

  1. 插入数据(create)
-- 插入单条数据(指定列)
insert into users (username, password, email, age) 
values ('john_doe', '123456', 'john@example.com', 25);
-- 插入单条数据(所有列)
insert into users values (null, 'jane_doe', '654321', 'jane@example.com', 30, now(), now());
-- 插入多条数据
insert into users (username, password, email) 
values 
    ('alice', 'pass123', 'alice@example.com'),
    ('bob', 'pass456', 'bob@example.com'),
    ('charlie', 'pass789', 'charlie@example.com');
  1. 查询数据(read)
-- 查询所有列
select * from users;
-- 查询指定列
select id, username, email from users;
-- 条件查询
select * from users where age > 20;
select * from users where username = 'john_doe';
select * from users where age between 20 and 30;
select * from users where email like '%@example.com';
-- 逻辑运算符
select * from users where age > 20 and email like '%@example.com';
select * from users where age < 18 or age > 60;
-- 排序
select * from users order by age desc;        -- 降序
select * from users order by created_at asc;  -- 升序
-- 限制返回数量
select * from users limit 10;                 -- 前10条
select * from users limit 5, 10;              -- 跳过5条,取10条
-- 去重
select distinct age from users;
-- 分组统计
select age, count(*) as count from users group by age;
select age, count(*) from users group by age having count(*) > 1;
-- 聚合函数
select count(*) as total_users from users;
select avg(age) as avg_age from users;
select max(age) as max_age from users;
select min(age) as min_age from users;
select sum(age) as total_age from users;
  1. 更新数据(update)
-- 更新单个字段
update users set email = 'new_email@example.com' where id = 1;
-- 更新多个字段
update users set 
    email = 'updated@example.com',
    age = 26,
    updated_at = now()
where username = 'john_doe';
-- 基于现有值更新
update users set age = age + 1 where age < 30;
-- 批量更新
update users set status = 'inactive' where last_login < '2024-01-01';
  1. 删除数据(delete)
-- 删除指定记录
delete from users where id = 1;
-- 删除多条记录
delete from users where age > 100;
-- 清空表(删除所有记录)
delete from users;
truncate table users;  -- 更快,不能回滚

四、高级查询技巧

  1. 连接查询
-- 内连接
select u.username, o.order_id, o.amount
from users u
inner join orders o on u.id = o.user_id;
-- 左连接
select u.username, o.order_id
from users u
left join orders o on u.id = o.user_id;
-- 右连接
select u.username, o.order_id
from users u
right join orders o on u.id = o.user_id;
  1. 子查询
-- where子句中的子查询
select * from users 
where age > (select avg(age) from users);
-- from子句中的子查询
select avg_age_table.age_group, count(*)
from (select 
    case 
        when age < 20 then '少年'
        when age between 20 and 40 then '青年'
        else '中老年'
    end as age_group
    from users) as avg_age_table
group by age_group;
  1. 联合查询
select username, email from active_users
union
select username, email from inactive_users;

五、事务处理

-- 开始事务
start transaction;
-- 执行操作
update accounts set balance = balance - 100 where user_id = 1;
update accounts set balance = balance + 100 where user_id = 2;
-- 提交或回滚
commit;  -- 确认更改
-- 或
rollback;  -- 撤销更改

六、实用技巧

  1. 备份数据
-- 创建表备份
create table users_backup as select * from users;
-- 插入备份数据
insert into users_backup select * from users where created_at > '2024-01-01';
  1. 批量操作
-- 批量插入(提高性能)
insert into users (username, email) values 
('user1', 'user1@example.com'),
('user2', 'user2@example.com'),
('user3', 'user3@example.com');
  1. 使用case表达式
select 
    username,
    age,
    case 
        when age < 18 then '未成年'
        when age between 18 and 60 then '成年'
        else '老年'
    end as age_group
from users;

注意事项

  1. where条件:update和delete操作一定要加where条件,除非确实要操作所有记录
  2. 事务处理:重要操作使用事务,确保数据一致性
  3. 索引使用:频繁查询的字段建议添加索引
  4. sql注入:应用程序中要使用参数化查询防止sql注入
  5. 性能优化:大数据量时注意查询性能,避免select *

到此这篇关于mysql - 基础增删查改的文章就介绍到这了,更多相关mysql增删查改内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

解决登录MySQL时提示ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost:3306‘ (10061)

01-31

MySQL对前N条数据求和的几种方案

01-31

MySQL数据库高危权限回收的实现

01-31

mysql配置环境变量实践(win10)

01-31

MySQL binlog日志进行手动删除与自动清理

01-31

Mysql的备份与恢复全过程(使用XtraBackup)

01-27

猜你喜欢

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

发表评论