MySQL CRUD 查詢、插入、更新、刪除全實戰(zhàn)指南
前言:
在 MySQL 日常開發(fā)中,CRUD(create/retrieve/update/delete)是最核心的高頻操作。掌握規(guī)范的 CRUD 語法、靈活的查詢技巧和避坑要點,能大幅提升開發(fā)效率和 SQL 可讀性。本文基于實戰(zhàn)場景,全面拆解 MySQL 的增刪改查操作,所有 SQL 語句均采用小寫形式,貼合實際開發(fā)規(guī)范,同時涵蓋聚合查詢、分組統(tǒng)計等進階內容。
一. 基礎準備:創(chuàng)建測試表與測試數據
為了讓所有示例更直觀,先創(chuàng)建兩張測試表并插入測試數據,后續(xù)操作均基于這兩張表:
- 語法:
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)
當主鍵或唯一鍵沖突時,不報錯而是執(zhí)行更新操作:
-- 主鍵沖突(id=100已存在),執(zhí)行更新 insert into students (id, sn, name) values (100, 10010, '唐大師') on duplicate key update sn = 10010, name = '唐大師'; // 同步更新語法 -- 唯一鍵沖突(sn=20001已存在),執(zhí)行更新 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 插入查詢結果
將一張表的查詢結果插入另一張表(常用于數據遷移、去重):
-- 創(chuàng)建空表(結構與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 全列查詢(不推薦)
-- 全列查詢(數據量大時性能差,不建議在生產環(huán)境使用) -- 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;
3.2 條件查詢(where)
通過比較運算符和邏輯運算符篩選數據,支持多種條件組合。
3.2.1 比較運算符
以下是您提供的運算符說明表格:
| 運算符 | 說明 |
|---|---|
| >, >=, <, <= | 大于、大于等于、小于、小于等于 |
| = | 等于(null 不安全,null = null 結果為 null) |
| <=> | 等于(null 安全,null <=> null 結果為 1) |
| !=, <> | 不等于 |
| between a and b | 范圍匹配([a, b]) |
| in (option...) | 匹配選項中的任意一個 |
| is null | 為空 |
| is not null | 不為空 |
| like | 模糊匹配(% 匹配任意字符,_ 匹配單個字符) |
3.2.2 邏輯運算符
| 運算符 | 說明 |
|---|---|
| and | 多個條件同時成立 |
| or | 任意一個條件成立 |
| not | 條件取反 |
3.2.3 條件查詢示例
-- 1. 英語不及格(<60) select name, english from exam_result where english < 60; -- 2. 語文成績在[80, 90]之間(between...and) select name, chinese from exam_result where chinese between 80 and 90; -- 3. 數學成績是58、59、98、99中的一個(in) select name, math from exam_result where math in (58, 59, 98, 99); -- 4. 姓孫的同學(like %) select name from exam_result where name like '孫%'; -- 5. 姓名是兩個字且姓孫(like _) select name from exam_result where name like '孫_'; -- 6. 語文成績好于英語成績 select name, chinese, english from exam_result where chinese > english; -- 7. 總分低于200分(表達式作為條件) select name, chinese + math + english as 總分 from exam_result where chinese + math + english < 200; // 不能直接用總分 < 20,因為執(zhí)行這里的時候還沒執(zhí)行前面的部分 -- 8. 語文>80且不姓孫(and + not) select name, chinese from exam_result where chinese > 80 and name not like '孫%'; -- 9. qq號不為空(is not null) select name, qq from students where qq is not null; -- 10. null安全比較(<=>) select name, qq from students where qq <=> null;
3.3 結果排序(order by)
默認升序(asc),可指定降序(desc),支持多字段排序。
-- 1. 按數學成績升序 select name, math from exam_result order by math; -- 2. 按數學降序,英語升序,語文升序 select name, math, english, chinese from exam_result order by math desc, english, chinese; -- 3. 按總分降序(表達式排序) select name, chinese + math + english as 總分 from exam_result order by 總分 desc; -- 4. null排序(null視為最小值,升序在最前) select name, qq from students order by qq; select name, qq from students order by qq desc;

3.4 分頁查詢(limit)
限制查詢結果數量,避免數據量過大導致性能問題,起始下標從 0 開始。
-- 語法1:limit 條數(取前n條) select * from exam_result order by id limit 3; -- 語法2:limit 起始下標, 條數(從s(下標從0開始)開始取n條) select * from exam_result order by id limit 3, 3; -- 語法3:limit 條數 offset 起始下標(推薦,更清晰) select * from exam_result order by id limit 3 offset 6; -- 分頁示例:每頁3條,第1-3頁 select * from exam_result order by id limit 3 offset 0; -- 第1頁 select * from exam_result order by id limit 3 offset 3; -- 第2頁 select * from exam_result order by id limit 3 offset 6; -- 第3頁

3.5 聚合查詢(聚合函數)
對查詢結果進行統(tǒng)計計算,常用聚合函數如下:
| 函數 | 說明 |
|---|---|
| count([distinct] expr) | 統(tǒng)計記錄數(distinct 去重) |
| sum([distinct] expr) | 求和(僅數字類型) |
| avg([distinct] expr) | 求平均值(僅數字類型) |
| max([distinct] expr) | 求最大值(僅數字類型) |
| min([distinct] expr) | 求最小值(僅數字類型) |
聚合查詢示例:
-- 1. 統(tǒng)計學生總數(count(*)不受null影響) select count(*) as 學生總數 from students; -- 2. 統(tǒng)計qq號非空的學生數(null不計入) select count(qq) as qq已收集人數 from students; -- 3. 統(tǒng)計數學成績總分和去重后總分 select sum(math) as 數學總分, sum(distinct math) as 去重數學總分 from exam_result; -- 4. 統(tǒng)計語文成績平均分 select avg(chinese) as 語文平均分 from exam_result; -- 5. 英語最高分和最低分 select max(english) as 英語最高分, min(english) as 英語最低分 from exam_result; -- 6. 統(tǒng)計70分以上的數學最低分 select min(math) as 70+數學最低分 from exam_result where math > 70;
3.6 分組查詢(group by + having)
group by按指定列分組,having篩選分組結果(類似where,但作用于分組)。
-- 準備雇員表(經典測試表) create table emp ( empno int primary key, ename varchar(20), job varchar(20), deptno int, sal float ); insert into emp values (7369, 'smith', 'clerk', 20, 800), (7499, 'allen', 'salesman', 30, 1600), (7521, 'ward', 'salesman', 30, 1250), (7566, 'jones', 'manager', 20, 2975), (7654, 'martin', 'salesman', 30, 1250), (7698, 'blake', 'manager', 30, 2850), (7782, 'clark', 'manager', 10, 2450), (7788, 'scott', 'analyst', 20, 3000); -- 1. 按部門分組,統(tǒng)計每個部門的平均工資和最高工資 select deptno, avg(sal) as 平均工資, max(sal) as 最高工資 from emp group by deptno; -- 2. 按部門和崗位分組,統(tǒng)計平均工資和最低工資 select deptno, job, avg(sal) as 平均工資, min(sal) as 最低工資 from emp group by deptno, job; -- 3. 篩選平均工資低于2000的部門(having篩選分組結果) select deptno, avg(sal) as 平均工資 from emp group by deptno having avg(sal) < 2000;




四. Update(更新數據)
修改表中已有數據,支持單字段、多字段更新,結合where、order by、limit精準控制更新范圍。
- 語法:
UPDATE table_name SET column = expr [, column = expr ...] [WHERE ...] [ORDER BY ...] [LIMIT ...]
-- 1. 更新單字段(孫悟空數學成績改為80) update exam_result set math = 80 where name = '孫悟空'; -- 2. 更新多字段(曹孟德數學60、語文70) update exam_result set math = 60, chinese = 70 where name = '曹孟德'; -- 3. 按表達式更新(所有同學語文成績翻倍) update exam_result set chinese = chinese * 2; -- 4. 結合排序和limit(總分倒數前三的同學數學+30) update exam_result set math = math + 30 order by chinese + math + english limit 3; -- 5. 條件更新(英語<60的同學英語+10) update exam_result set english = english + 10 where english < 60;
- 警告:無
where子句會更新全表數據,生產環(huán)境需謹慎
五. Delete(刪除數據)
刪除表中數據,支持條件刪除、全表刪除,還有高效的truncate截斷表。
5.1 條件刪除
-- 1. 刪除孫悟空的考試成績 delete from exam_result where name = '孫悟空'; -- 2. 刪除英語<60的同學成績 delete from exam_result where english < 60;
5.2 全表刪除(delete)
-- 刪除for_delete表所有數據(自增id不重置)
create table for_delete (
id int primary key auto_increment,
name varchar(20)
);
insert into for_delete (name) values ('a'), ('b'), ('c');
delete from for_delete;
-- 插入新數據,自增id從4開始
insert into for_delete (name) values ('d');
select * from for_delete; -- id=4
5.3 截斷表(truncate)
快速刪除全表數據,重置自增 id,比delete更高效(不記錄事務):

-- 截斷表(自增id重置為1)
create table for_truncate (
id int primary key auto_increment,
name varchar(20)
);
insert into for_truncate (name) values ('a'), ('b'), ('c');
truncate for_truncate;
-- 插入新數據,自增id從1開始
insert into for_truncate (name) values ('d');
select * from for_truncate; -- id=1- 區(qū)別:
delete是逐行刪除(可回滾),truncate直接重置表(不可回滾),效率更高。
六. SQL 執(zhí)行順序與避坑指南
6.1 SQL 關鍵字執(zhí)行順序
from → on → join → where → group by → with → having → select → distinct → order by → limit
- 別名不能在
where中使用(select在where之后執(zhí)行); having用于篩選分組結果(group by之后執(zhí)行),where用于篩選行數據(group by之前執(zhí)行)。

6.2 避坑要點和總結
- 避免全列查詢:僅查詢需要的列,減少數據傳輸和內存占用;
null判斷用is null/is not null:=和!=對null無效;- 更新 / 刪除必加
where:防止誤操作全表數據; - 分頁查詢必加
order by:避免分頁結果混亂; - 聚合函數忽略
null:count(qq)不計入qq為null的記錄; truncate不可回滾:刪除全表數據優(yōu)先考慮delete(需回滾)或truncate(高效)。
總結: MySQL CRUD 是數據庫開發(fā)的基礎,核心要點:
- 插入數據支持單行 / 多行、沖突處理、查詢結果插入;
- 查詢是核心,靈活組合
where、order by、limit、聚合函數、分組查詢滿足復雜需求; - 更新 / 刪除需精準控制范圍,避免全表操作;
- 遵循 SQL 執(zhí)行順序,避開
null判斷、別名使用等常見坑。
到此這篇關于MySQL CRUD 查詢、插入、更新、刪除全實戰(zhàn)指南的文章就介紹到這了,更多相關mysql crud 查詢 插入更新刪除內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

