MySQL CRUD 核心指南:查询、插入、更新、删除全实战

一. 基础准备:创建测试表与测试数据

为了让所有示例更直观,先创建两张测试表并插入测试数据,后续操作均基于这两张表:

  • 语法
  • INSERT [INTO] table_name
    [(column [, column] ...)]
    VALUES (value_list) [, (value_list)] ...

    value_list: value, [, value] ...

1.1 学生表(students

create table students (
id int unsigned primary key auto_increment,
sn int not null unique comment '学号',
name varchar(20) not null,
qq varchar(20)
);

-- 插入测试数据
insert into students values
(100, 10000, '唐三藏', null),
(101, 10001, '孙悟空', '11111'),
(102, 20001, '曹孟德', null),
(103, 20002, '孙仲谋', null);

1.2 考试成绩表(exam_result)

create table exam_result (
id int unsigned primary key auto_increment,
name varchar(20) not null comment '同学姓名',
chinese float default 0.0 comment '语文成绩',
math float default 0.0 comment '数学成绩',
english float default 0.0 comment '英语成绩'
);

-- 插入测试数据
insert into exam_result (name, chinese, math, english) values
('唐三藏', 67, 98, 56),
('孙悟空', 87, 78, 77),
('猪悟能', 88, 98, 90),
('曹孟德', 82, 84, 67),
('刘玄德', 55, 85, 45),
('孙权', 70, 73, 78),
('宋公明', 75, 65, 30);

二. Create(插入数据)

插入数据核心是insert语句,支持单行 / 多行插入、指定列插入、冲突处理等场景。

2.1 单行全列插入

插入数据需与表结构的列数和顺序完全一致(自增主键可省略,自动生成):

-- 全列插入(指定id)
insert into students values (104, 20003, '鲁智深', '22222');

-- 省略自增主键(自动生成id)
insert into students (sn, name, qq) values (20004, '林冲', '33333');

2.2 多行指定列插入

一次插入多条数据,仅指定需要赋值的列,未指定列使用默认值或null

insert into students (sn, name) values
(20005, '武松'),
(20006, '杨志');

2.3 插入冲突处理(on duplicate key update)

当主键或唯一键冲突时,不报错而是执行更新操作:

-- 主键冲突(id=100已存在),执行更新
insert into students (id, sn, name) values (100, 10010, '唐大师')
on duplicate key update sn = 10010, name = '唐大师'; // 同步更新语法

-- 唯一键冲突(sn=20001已存在),执行更新
insert into students (sn, name) values (20001, '曹阿瞒')
on duplicate key update name = '曹阿瞒';

2.4 替换插入(replace into)

主键或唯一键冲突时,删除原记录后重新插入:

-- sn=20002已存在,删除原记录后插入新数据
replace into students (sn, name) values (20002, '孙伯符');

2.5 插入查询结果

将一张表的查询结果插入另一张表(常用于数据迁移、去重):

-- 创建空表(结构与students一致)
create table students_copy like students;

-- 将students的去重数据插入新表
insert into students_copy select distinct * from students;

三. Retrieve(查询数据)

查询是 CRUD 中最复杂的操作,支持全列查询、条件查询、排序、分页、聚合等功能,核心语法:

select
[distinct] {* | column [, column] ...}
from table_name
[where ...]
[order by column [asc | desc], ...]
limit ...

3.1 基础查询

3.1.1 全列查询(不推荐)

-- 全列查询(数据量大时性能差,不建议在生产环境使用)
-- 1. 查询的列越多,意味着需要传输的数据量越大
-- 2. 可能会影响到索引的使用。(索引待后面我们再进行理解)
select * from exam_result;

3.1.2 指定列查询

-- 查询姓名、语文、数学成绩
select name, chinese, math from exam_result;

3.1.3 查询表达式

支持常量、单字段运算、多字段运算:

-- 常量表达式
select id, name, 10 from exam_result;

-- 单字段运算(英语成绩+10)
select id, name, english + 10 from exam_result;

-- 多字段运算(总分)
select id, name, chinese + math + english from exam_result;

3.1.4 结果别名(as 可省略)

给查询结果列指定别名,增强可读性:

select
id,
name,
chinese + math + english as 总分
from exam_result;

3.1.5 结果去重(distinct

去除查询结果中的重复记录:

-- 去重查询数学成绩 distinct
select distinct math from exam_result;

 

上一篇 统信系统中应用商店下载软件失败或提示依赖错误的处理方法
下一篇 【Linux】sudo 命令提升权限的使用技巧