MySQL中CRUD操作及常用查詢語法舉例詳解
Mysql-CURD
CRUD : Create(創(chuàng)建), Retrieve(讀取),Update(更新),Delete(刪除)。
1. Create
語法:
INSERT [INTO] table_name [(column [, column] ...)] VALUES (value_list) , (value_list) , ...;
案例:
CREATE TABLE students (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
sn INT NOT NULL UNIQUE COMMENT '學號',
name VARCHAR(20) NOT NULL,
qq VARCHAR(20)
);
1.1 單行數(shù)據(jù) + 全列插入
inser into students values (1, 20250123, 'Jack' , NULL);
1.2 多行數(shù)據(jù) + 指定列插入
inser into (sn , name , qq) students values (20250124, 'ali' , "123456789") , (20250125 , "alger" , "23456781");
1.3 插入否則更新
1.3.1 on duplicate key
主鍵 或者 唯一鍵 沒有沖突,則直接插入。
主鍵 或者 唯一鍵 如果沖突,則刪除后再插入。
語法:
INSERT ... ON DUPLICATE KEY UPDATE column = value [, column = value] ...
案例:
insert into students values (1 , 20250126 , "Jack" , "345678912") on duplicate key update sn = 20250126;
0 row affected:表中有沖突數(shù)據(jù),但沖突數(shù)據(jù)的值和 update 的值相等。
1 row affected:表中沒有沖突數(shù)據(jù),數(shù)據(jù)被插入。
2 row affected:表中有沖突數(shù)據(jù),并且數(shù)據(jù)已經(jīng)被更新。
1.3.2 replace
語法:
REPLACE ... ON DUPLICATE KEY UPDATE column = value [, column = value] ...
2. Retrieve
語法:
SELECT
[DISTINCT] {* | {column [, column] ...}
[FROM table_name]
[WHERE ...]
[ORDER BY column [ASC | DESC], ...]
LIMIT ...
2.0 select 順序
SQL SELECT 語句的典型執(zhí)行順序為:
FROM(指定數(shù)據(jù)來源表,是查詢的基礎)。WHERE(篩選行,對 FROM 后的結果進行條件過濾)。SELECT(指定要查詢的列或表達式)。ORDER BY(對結果集排序)。LIMIT(限制結果集的行數(shù),多用于分頁等場景)。

案例:
# 案例
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 '數(shù)學成績',
english float DEFAULT 0.0 COMMENT '英語成績'
);
# 插入數(shù)據(jù)
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);
2.1 全列查詢
select * from exam_result;
2.2 指定列查詢
select id , name , english from exam_result;
2.3 查詢并計算臨時表達式
select id , name , english + chinese + math from exam_result;
2.4 為2.3起別名
select id , name , english + chinese + math as total from exam_result;
select id , name , english + chinese + math total from exam_result;
2.5 查詢結果去重
select distinct math from exam_result;
2.6 where 條件
2.6.1 運算符
比較運算符:
| 運算符 | 說明 |
|---|---|
| >, >=, <, <= | 大于,大于等于,小于,小于等于 |
| = | 等于,NULL 不安全,例如 NULL = NULL 的結果是 NULL |
| <=> | 等于,NULL 安全,例如 NULL <=> NULL 的結果是 TRUE(1) |
| !=, <> | 不等于,區(qū)分 NULL 安全與 NULL 不安全 |
| BETWEEN a0 AND a1 | 范圍匹配,[a0, a1],返回 TRUE(1) |
| IN (option, …) | 如果是 option 中的任意一個,返回 TRUE(1) |
| IS NULL | 是 NULL |
| IS NOT NULL | 不是 NULL |
| LIKE | 模糊匹配。% 表示任意多個(包括 0 個)任意字符;_ 表示任意一個字符 |
邏輯運算符:
| 運算符 | 說明 |
|---|---|
| AND | 多個條件必須都為 TRUE(1),結果才是 TRUE(1) |
| OR | 任意一個條件為 TRUE(1), 結果為 TRUE(1) |
| NOT | 條件為 TRUE(1),結果為 FALSE(0) |
2.6.2 英語不及格的同學及英語成績
select name , english from exam_result where english < 60;
2.6.3 語文成績在 [80, 90] 分的同學及語文成績
select name , chinese from exam_result where chinese >= 80 and chinese <= 90; select name , chinese from exam_result where chinese between 80 and 90;
2.6.4 數(shù)學成績是 58 或者 59 分的同學及數(shù)學成績
select name , math from exam_result where math = 58 or math = 59; select name , math from exam_result where math in (58 , 59);
2.6.5 姓孫的同學及孫某同學
select name from exam_result where name like "孫%"; # 孫悟空、孫權 select name from exam_result where name like "孫_"; # 孫權
2.6.5 語文成績好于英語成績的同學
select name , chinese , english from exam_result where chinese > english;
2.6.6 總分在200分以下的同學
select name , chinese + math + english total from exam_result where chinese + math + english < 200;
注意:total 不可以在 where 子句中使用。
2.6.7 不是孫某同學
select name from exam_result where name not like "孫_";
2.6.8 name不是NULL的
select name from exam_result where name is not null;
2.7 order by
asc 升序(默認)。
desc 降序。
語法:
SELECT ... FROM table_name [WHERE ...] ORDER BY column [ASC|DESC], [...];
2.7.1 同學及數(shù)學成績,按數(shù)學成績升序顯示
select name , math from exam_result order by math;
2.7.2 查詢同學各門成績,依次按 數(shù)學降序,英語升序,語文升序的方式顯示
select name , math , english , chinese from exam_result order by math desc , english asc , chinese asc;
2.7.3 查詢姓孫的同學或者姓曹的同學數(shù)學成績,結果按數(shù)學成績由高到低顯示
select name , math from exam_result where name like "孫%" or name like "曹%" order by math desc;
2.8 limit
語法:
# 起始下標為 0 # 從 0 開始,篩選 n 條結果 SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n; # 從 s 開始,篩選 n 條結果 SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT s, n; # 從 s 開始,篩選 n 條結果,比第二種用法更明確,建議使用 SELECT ... FROM table_name [WHERE ...] [ORDER BY ...] LIMIT n OFFSET s;
2.8.1 按 id 進行分頁,每頁 3 條記錄,分別顯示 第 1、2、3 頁。
select id , name , math , chinese , english from exam_result order by id asc limit 0,3; select id , name , math , chinese , english from exam_result order by id asc limit 3,3; select id , name , math , chinese , english from exam_result order by id asc limit 6,3;
3. Update
語法:
UPDATE table_name SET column = expr [, column = expr ...]
[WHERE ...] [ORDER BY ...] [LIMIT ...]
對查詢到的結果進行列值更新。
3.1 將孫悟空同學的數(shù)學成績變更為 80 分
update exam_result set math = 80 where name = "孫悟空";
3.2 將總成績倒數(shù)前三的 3 位同學的數(shù)學成績加上 30 分
update exam_result set math = math + 30 order by chinese + math + english asc limit 3;
3.3 將所有人的數(shù)學成績更新為原來的2倍
update exam_result set math = math * 2;
注意:update通常需要判斷條件,更新全表的語句慎用!
4. Delete
語法:
DELETE FROM table_name [WHERE ...] [ORDER BY ...] [LIMIT ...]
4.1 刪除孫悟空
delete from exam_result where name = "孫悟空";
4.2 刪除整表內容
delete from exam_result;
慎用!
5. 插入查詢結果
語法:
INSERT INTO table_name [(column [, column ...])] SELECT ...
1?? 創(chuàng)建一個表,結構復制 exam_result 表。
create table no_duplicate_table like exam_result;
2?? 將 exam_result 查詢的結果插入到 no_duplicate_table 表。
insert into no_duplicate_table select id , name , chinese , math , english from exam_result;
6. 聚合函數(shù)
| 函數(shù) | 說明 |
|---|---|
| COUNT([DISTINCT] expr) | 返回查詢到的數(shù)據(jù)的 數(shù)量 |
| SUM([DISTINCT] expr) | 返回查詢到的數(shù)據(jù)的 總和,不是數(shù)字沒有意義 |
| AVG([DISTINCT] expr) | 返回查詢到的數(shù)據(jù)的 平均值,不是數(shù)字沒有意義 |
| MAX([DISTINCT] expr) | 返回查詢到的數(shù)據(jù)的 最大值,不是數(shù)字沒有意義 |
| MIN([DISTINCT] expr) | 返回查詢到的數(shù)據(jù)的 最小值,不是數(shù)字沒有意義 |
6.1 統(tǒng)計表中有多少行
select count(*) from exam_result;
NULL不計入結果。
select count(distinct col) from table-name 統(tǒng)計去重的結果。
6.2 統(tǒng)計數(shù)學總成績
select sum(math) from exam_result;
6.3 統(tǒng)計不及格同學的數(shù)學總成績
select sum(math) from exam_result where math < 60;
6.4 統(tǒng)計平均分
select avg(chinese + math + english) from exam_result;
6.5 返回英語最高分
select max(english) from exam_result;
6.6 返回數(shù)學最低分
select min(math) from exam_result;
注意:select name, min(math) from exam_result;
報錯信息:只有按 name 分組后才可以這樣使用,可通過 where order by limit方式查詢。
7. group by子句
在 select 中使用 group by子句可以對指定列進行分組查詢,通常與聚合函數(shù)一起使用。
準備工作:創(chuàng)建一個雇員信息表(Oracle 9i經(jīng)典測試表)
DROP database IF EXISTS `scott`; CREATE database IF NOT EXISTS `scott` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE `scott`; DROP TABLE IF EXISTS `dept`; CREATE TABLE `dept` ( `deptno` int(2) unsigned zerofill NOT NULL COMMENT ' 部門編號 ', `dname` varchar(14) DEFAULT NULL COMMENT ' 部門名稱 ', `loc` varchar(13) DEFAULT NULL COMMENT ' 部門所在地點 ' ); DROP TABLE IF EXISTS `emp`; CREATE TABLE `emp` ( `empno` int(6) unsigned zerofill NOT NULL COMMENT '雇員編號', `ename` varchar(10) DEFAULT NULL COMMENT '雇員姓名', `job` varchar(9) DEFAULT NULL COMMENT '雇員職位', `mgr` int(4) unsigned zerofill DEFAULT NULL COMMENT '雇員領導編號', `hiredate` datetime DEFAULT NULL COMMENT '雇傭時間', `sal` decimal(7,2) DEFAULT NULL COMMENT '工資月薪', `comm` decimal(7,2) DEFAULT NULL COMMENT '獎金', `deptno` int(2) unsigned zerofill DEFAULT NULL COMMENT '部門編號' ); DROP TABLE IF EXISTS `salgrade`; CREATE TABLE `salgrade` ( `grade` int(11) DEFAULT NULL COMMENT '等級', `losal` int(11) DEFAULT NULL COMMENT '此等級最低工資', `hisal` int(11) DEFAULT NULL COMMENT '此等級最高工資' ); insert into dept (deptno, dname, loc) values (10, 'ACCOUNTING', 'NEW YORK'); insert into dept (deptno, dname, loc) values (20, 'RESEARCH', 'DALLAS'); insert into dept (deptno, dname, loc) values (30, 'SALES', 'CHICAGO'); insert into dept (deptno, dname, loc) values (40, 'OPERATIONS', 'BOSTON'); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7369, 'SMITH', 'CLERK', 7902, '1980-12-17', 800, null, 20); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7499, 'ALLEN', 'SALESMAN', 7698, '1981-02-20', 1600, 300, 30); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7521, 'WARD', 'SALESMAN', 7698, '1981-02-22', 1250, 500, 30); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7566, 'JONES', 'MANAGER', 7839, '1981-04-02', 2975, null, 20); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7654, 'MARTIN', 'SALESMAN', 7698, '1981-09-28', 1250, 1400, 30); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7698, 'BLAKE', 'MANAGER', 7839, '1981-05-01', 2850, null, 30); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7782, 'CLARK', 'MANAGER', 7839, '1981-06-09', 2450, null, 10); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7788, 'SCOTT', 'ANALYST', 7566, '1987-04-19', 3000, null, 20); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7839, 'KING', 'PRESIDENT', null, '1981-11-17', 5000, null, 10); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7844, 'TURNER', 'SALESMAN', 7698,'1981-09-08', 1500, 0, 30); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7876, 'ADAMS', 'CLERK', 7788, '1987-05-23', 1100, null, 20); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950, null, 30); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7902, 'FORD', 'ANALYST', 7566, '1981-12-03', 3000, null, 20); insert into emp (empno, ename, job, mgr, hiredate, sal, comm, deptno) values (7934, 'MILLER', 'CLERK', 7782, '1982-01-23', 1300, null, 10); insert into salgrade (grade, losal, hisal) values (1, 700, 1200); insert into salgrade (grade, losal, hisal) values (2, 1201, 1400); insert into salgrade (grade, losal, hisal) values (3, 1401, 2000); insert into salgrade (grade, losal, hisal) values (4, 2001, 3000); insert into salgrade (grade, losal, hisal) values (5, 3001, 9999);
在 Oracle 9i 的經(jīng)典測試表(
SCOTT用戶下的EMP和DEPT表)中,deptno字段的外鍵關系是邏輯上的、約定俗成的,而不是通過數(shù)據(jù)庫物理外鍵約束(Foreign Key Constraint)強制實現(xiàn)的。
7.1 顯示每個部門的平均工資和最高工資
select deptno , avg(sal) , max(sal) from emp group by deptno;
SELECT 子句中的字段,要么必須包含在 GROUP BY 子句中,要么必須被包含在聚合函數(shù)(如 AVG, MAX, SUM, COUNT 等)中。
group by理解為分組,也可以理解為分表。
7.2 顯示每個部門不同崗位的平均工資和最低工資
select deptno , job, avg(sal) , min(sal) from emp group by deptno , job;
7.3 having
having 和 group by 配合使用,對 group by 結果進行過濾。
7.3.1 查詢每個部門的平均工資,并只顯示那些平均工資低于 2000 的部門
select avg(sal) from emp group by deptno having avg(sal) < 2000;
7.3 having 和 where 的區(qū)別
7.3.1 查詢每個部門的平均工資(但不包括員工名 SMITH 的員工數(shù)據(jù))。
select deptno , avg(sal) from emp where ename != "SMITH" group by deptno;
簡單的比喻:
WHERE是原材料質檢員,在加工(分組聚合)前就把爛蘋果(不合格的行)扔掉。HAVING是成品質檢員,在加工(分組聚合)完成后,檢查做好的蘋果罐頭(分組結果),把不合格的整批罐頭扔掉。
where 之后,也是一個表。where 本質是先過濾出你想要分組的表,之后再通過 group by 進行分組。
8. SQL查詢中各個關鍵字的執(zhí)行順序
from > on > join > where > group by > with > having > select > distinct > order by > limit
總結
到此這篇關于MySQL中CRUD操作及常用查詢語法舉例詳解的文章就介紹到這了,更多相關MySQL CRUD操作及查詢語法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MYSQL的binary解決mysql數(shù)據(jù)大小寫敏感問題的方法
BINARY不是函數(shù),是類型轉換運算符,它用來強制它后面的字符串為一個二進制字符串,可以理解為在字符串比較的時候區(qū)分大小寫2013-09-09
mysql8.0.43使用InnoDB?Cluster配置主從復制
本文主要介紹了mysql8.0.43使用InnoDB?Cluster配置主從復制,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-09-09
MySQL 數(shù)據(jù)庫 binLog 日志的使用操作
binlog是MySQL數(shù)據(jù)庫中的一種日志類型,它記錄了數(shù)據(jù)庫中的所有更改操作,例如插入、更新、刪除操作,本文給大家介紹MySQL 數(shù)據(jù)庫 binLog 日志的使用,感興趣的朋友一起看看吧2023-08-08
mysql如何用sql語句建立學生課程數(shù)據(jù)庫基本表
這篇文章主要給大家介紹了關于mysql如何用sql語句建立學生課程數(shù)據(jù)庫基本表的相關資料,學生表是一個常見的數(shù)據(jù)表,用于存儲學生的個人信息和成績等相關數(shù)據(jù),文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-12-12

