mysql数据库,语法语句总结。以及事务理解-基础篇
文章目錄
- 數據庫
- **Sql語句**
- **DDL語句**
- **操作數據庫**
- **操作數據庫的表結構**
- **表結構的修改:**
- **sql數據類型:**
- **DML語句(增刪改)**
- **插入數據**
- **刪除數據**
- **修改數據**
- **DQL語句(查詢)**
- **基本查詢**
- **條件查詢**
- **綜合操作查詢**
- **DCL控制語句**
- **函數**
- **數值函數**
- **日期函數:**
- **約束**
- **多表查詢**
- **內連接**
- **外連接**
- **自連接**
- **聯合查詢**
- **子查詢**
- **標量子查詢**
- **列子查詢**
- **行子查詢**
- **表子查詢**
- 事務
- 事務的隔離級別(由低到高,性能由高到低)
- 讀未提交 等級 1
- 讀已提交 等級 2
- 可重復讀 等級4
- 串行化隔離 等級8
- 數據庫進階
數據庫
mysql概述
Sql語句
在命令行窗口中,都是以分號結尾的。
DDL語句
操作數據庫
show databases; -- 都有默認的設置 "[]"不是sql里的 create database if not exists [數據庫名]; create database [ if not exists] [數據庫名] [default charset utf-8] [COLLATE 排序規則]; drop database [if exists] [數據庫名]; use [數據庫名] ; -- 查看當前使用的數據庫 select database();操作數據庫的表結構
要選中數據庫再執行sql語句
-- 查詢當前數據庫的所有表 show tables; -- 創建表結構 create table [表名] (字段1 字段1的數據類型 [comment '注釋'],字段2 字段2的數據類型 [comment '注釋'],字段3 字段3的數據類型 [comment '注釋'],...字段n 字段n的數據類型 [comment '注釋'] )[comment '注釋']; -- 查看表結構,但是查看不到注釋的詳細信息 desc [表名] -- 查看表結構的詳細信息 show create table [表名];表結構的修改:
-- 往表結構中添加一個新的字段 alter table [表名] add [字段名 類型(長度)] [comment '注釋']; -- 修改表結構中的字段名 alter table [表名] change [舊字段名 新字段名 數據類型(長度)] ; -- 修改表的某個字段類型 alter table [表名] modify [字段名 新數據類型(長度)] [comment '注釋'] [約束]; -- 刪除表字段 alter table [表名] drop [字段名]; -- 修改表名 alter table [表名] rename to [新表名]; -- 刪除表 drop table [表名]; -- 刪除指定表 ,并重新創建表 truncate table [表名];sql數據類型:
數值類型
| tinyint | 1byte | (-128,127) | (0,255) | 小整數值 |
| smallint | 2字節 | (-3276,3227) | (0,65535) | 大整數值 |
| MEdiumint | 3字節 | (8388608,8388609) | (0,16777215 | 大整數值 |
| int/integer | 4bytes | 很大 | 很大 | 大整數值 |
| bigint | 8bytes | 很大 | 很大 | 極大整數值 |
| double | 8bytes | ~ | ~ | 雙精度浮點值 |
| float | 4bytes | ~ | ~ | 單精度浮點數值 |
| decima | 依賴于M精度和D標度的值 | 小數值(精確定點數) |
字符類型:
變長,定長-性能-內存\
二進制文件、文件的存儲形式,長文本數據
| char | 0-255bytes | 變長字符串 |
| varchar | 0-65535bytes | 變長字符串 |
| tinyBlob | 0-255bytes | 不超過255個字符的二進制 |
| Blob | 0-255bytes | 二進制的長文本數據 |
| Text | 0-65535bytes | 長文本數據 |
| long blob | 0-4294 9672 95bytes | 二進制形式的極大文本數據 |
| long text | 0-4294 9672 95bytes | 極大文本數據 |
日期時間類型:
| date | 3 | 1000-01-01至9999-12-31 | YYYY-MM-DD | 日起值 |
| time | 3 | -838:59:59 至 838:59:59 | HH:MM:SS | 時間值或持續時間 |
| YEAR | 1 | 1901至2155 | YYYY | 年份值 |
| DateTime | 8 | 1000-01-01 00:00:00 至 9999-12-3123:59:59 | YYYY-MM-DD HH:MM:SS | 混合日期和時間值 |
| TIMESTARP | 4 | 1000-01-01 00:00:00 至 9999-12-3123:59:59 | YYYY-MM-DD HH:MM:SS | 混合日期和時間值 |
圖形化界面安裝:
DML語句(增刪改)
DML-介紹:DML英文全稱是Data Manipulate Language(數據操作語言) ,用來對數據庫中表的數據記錄進行增刪改操作
- 添加數據: insert
- 刪除數據 delete
- 修改數據 update
插入數據
-- 給指定數據添加數據 insert into 表名 (字段1,字段2 ,...) values (值1,值2,...); -- 給全部字段添加數據,不能少,且要一一對應 insert into [表名] values(值1,值2,...); -- 批量添加數據 insert into [表名](字段1,字段2 ,...) values (值1,值2,...),(值1,值2,...),(值1,值2,...),(值1,值2,...),...; insert into [表名]values(值1,值2,...),(值1,值2,...),(值1,值2,...),...;-- 不能少字段刪除數據
-- 根據where條件刪除一條記,如果沒有where語句則會刪除整張表的記錄 -- delete語句不能刪除莫一個字段的值 delete from [表名] where id = 1;修改數據
-- 按照where條件修改記錄,如果沒有帶where條件則修改整張表的記錄 update [表名] set [ 字段1 = 值1 ,字段2 = 值2,... ] [where 條件];DQL語句(查詢)
DQL-介紹:數據查詢語言
- 查詢關鍵字 select
DQL-語法
select [字段列表] from [表名] where [條件列表] Group By [分組字段列表] having [分組后列表查詢] order by[排序字段列表] Limt [分頁參數]基本查詢
-- 查詢多個字段 select * from [表名]; select [字段1 as 別名 , 字段2 as 別名, ...] from [表名]; -- 在查詢結果中,去除重復記錄 ,distinct 只能去除單個字段,不能在整個記錄中起作用 select DIstinct [字段列表] from [表名];條件查詢
-- 語法形式 select [字段列表] from [表名] where 條件列表;| > | 大于 |
| < | 小于 |
| >= | 大于等于 |
| <= | 小于等于 |
| = | 等于 |
| <> 或 != | 不等于 |
| between…and… | 在某個范圍之間(含最小值,含最大值) |
| in(…) | 在in 之后的列表中的值,多選一 |
| LIKE 占位符 | 模糊匹配(_匹配單個字符,%匹配任意個字符) |
| is null | 是 空 |
| AND 或 && | 并且 |
| OR 或 || | 或 |
| Not 或 ! | 非 |
條件查詢的實操
select * from smbms_user where id = 1; select * from smbms_user where userRole <= 2; select * from smbms_user where modifyBy is null; select * from smbms_user where modifyBy is not null; select * from smbms_user where userRole != 3; select * from smbms_user where userRole >=1 and userRole<=3; select * from smbms_user where userRole between 1 and 3; select * from smbms_user where gender = 2 and userRole<3; select * from smbms_user where gender = 2 || userRole<3; select * from smbms_user where userRole in(1,2); -- 匹配查詢,‘_’標識一個字符,%表示任意一個字符 select * from smbms_user where like '__'; -- phone末尾為4的記錄 select * from smbms_user where phone like '%4'; -- phone 第二個字符為4的記錄 select * from smbms_user where phone like '_4%'; -- phone從第二個開始到最后有8的記錄 select * from smbms_user where phone like '_%8%'; -- phone不含有4到7的記錄,這里的中括號是正則表達式,有用的 select * from smbms_user where phone not like '%[4-5]%'; select * from smbms_user where phone like '%8%';聚合函數:
概念:將一列數據作為一個整體的縱向計算
| count | 統計數量 |
| max | 該列的最大值 |
| min | 該列的最小值 |
| avg | 該列的平均值 |
| sum | 該列的總值 |
實例操作
-- 所有都不會統計null 的計算 select count(*) from emp; select count(usernName) from emp; -- 其他 select avg(age) from emp; select max(age) from emp; select min(age) from emp; select sum(age) frme emp where address = '江西';分組查詢
-- where 和 having 的區別 -- where 是分組之前進行過濾,判斷條件不同,不能操縱聚合函數 -- having是分組之后進行過濾,判斷條件不同,可以操縱聚合函數 select [字段列表] from [表名] where [條件] group by [分組字段名] having [分組后過濾條件];實例操作
select gender,count(*) from emp group by gender ; select gebder ,avg(age) from emp group by gender; -- 查詢年齡小于45,并根據地址分組,獲取員工數量大于等于3的地區。 select address, count(*) from emp where age< 45 group by address having count(*)>=3;執行優先級: where > 聚合函數 > having
分組之后,查詢的字段一般為聚合函數和分組字段,查詢其他字段是沒有任何意義的
排序查詢
- 關鍵字 order by
- ASC 升序 ,默認值
- DESC 降序
注意:如果是多字段排序,當第一個字段值相同時,才會根據第二個字段排序
select [字段列表] from [表名] order by [字段1 排序方式1],[字段2 排序方式2],...;實例操作
-- 查詢emp表,按照工作id 升序排序 select * from emp order by job_id asc; -- 查詢員工表,根據工作id升序排序后,再根據管理員工號排序 select * from emp order by job_id asc,mgr desc;分頁查詢
注意:
- 起始索引是從0開始的,起始索引 = (查詢頁碼-1)* 頁碼顯示的記錄數;
- 分頁查詢是各個數據庫方言,各有不同。MySQL可能與orcale 不同
- 如果查詢時第一頁數據,起始索引可以省略,直接寫成limit 10;
實例操作
-- 分頁查詢 select * from emp order by id asc limit 0 ,3 select * from emp order by id asc limit 3,3;綜合操作查詢
注意:執行順序
表名(from)—>條件列表(where)—>分組字段列表(group by)—>字段列表(select)—>排序字段列表(order)–>分頁參數(limit)
select * from emp where job_id = 4 and salary between 7000.0 and 20000.0 and ename like '___'; -- select ename,salary ,joindate from emp where salary < 14000.00 order by salary asc ,joindate; -- select ename,salary ,joindate,job_id from emp where salary < 14000.00 order by job_id desc, salary asc ; -- select * from emp where job_id in (2,3,4) and salary between 6000.00 and 15000.00 order by job_id asc ,salary desc limit 4,4;DCL控制語句
DCL:用來管理數據庫用戶,控制數據庫的訪問和權限
注意:主機可以使用% 進行通配
這類sql 人員操作較少,主要是DBA(數據庫管理人員)使用。
sql語句如下:
-- 查尋數據庫用戶 Use mysql; select * from user; -- 創建用戶 create user '用戶名' @'主機名' identified by '密碼'; create user 'itpsz' @'localhost' identified by '123456'; -- 創建的用戶 pszit ,可以在任意的主機上訪問該數據庫,密碼為123456; create user 'pszit'@'%' identified by '123456'; -- 修改密碼命令 alter user '用戶名'@'%' identified with mysql_native_password by '1234567'; -- 刪除用戶 drop user '用戶名'@'localhost';DQL-權限控制
| ALL,ALL PRIVILEGES | 所有權限 |
| SELECT | 查詢數據 |
| INSERT | 添加數據 |
| UPDATE | 修改數據 |
| DELETE | 刪除數據 |
| ALTER | 修改表 |
| DROP | 刪除數據庫/表/視圖 |
| CREATE | 創建數據庫/表 |
函數
什么是函數:函數是指一段可以被另一段程序調用的程序代碼
字符串函數:主要是統一修改數據庫字段的規范
| contact (s1,s2,…,sn) | 字符串拼接,s1,s2,…sn,拼接成一個字符串 |
| lower(str) | 將字符串str全部轉為小寫 |
| upper(str) | 將字符串str全部轉為大寫 |
| lpad(str, n ,pad) | 左填充,用字符串pad對str的左邊進行填充,達到n個字符傳長度 |
| Rpad(str ,n, pad) | 右填充 |
| trim (str) | 去掉字符串頭部和尾部的空格 |
| substring(str,start,len) | 返回字符串str從start位置起的len個長度的字符串 |
實例操作
-- 業務規范需求,要求工號id必須是五位數,不足五位數的左側補0 update emp set id = lpad(id,5,0);數值函數
| ceil(x) | 向上取整 |
| floor(x) | 向下取整 |
| mod() | 返回x/y的模 |
| rand() | 返回0~1內的隨機數 |
| round(x,y) | 求參數x的四舍五入的值,保留y位小數 |
實操實例:
-- 通過數據庫的函數,生成一個隨機的驗證碼 select lpad(round(rand()*100000,0),6,0);日期函數:
| curdate() | 返回當前的日期 |
| curtime() | 返回當前的時間 |
| now() | 返回當前的日期和時間 |
| year(date) | 獲取指定的date年份 |
| month(date) | 獲取指定的date月份 |
| day(date) | 獲取指定date的日期 |
| date_add(date,interval expr type) | 返回一個日期/時間值加上一個時間間隔expr 后的時間 |
| datediff(date1,date2) | 返回起始時間date1和截止時間date2之間的天數 |
| if(value ,t,f) | 如果value 為true,則返回t,否則f |
| if null (value1,value2) | 如果value值不為null,返回value1,否則value2 |
| case [字段名] when [value1] than [res1] …else[default] end | 如果value 為true,返res1否則返回默認值 |
| case [expr] when [value] than [res1] … eles[default] end | 如果expr的值等于value1,返回expr,否則返回默認值 |
流程函數:流程函數也是很常用的一類函數,可以在sql中實現條件的篩選,從而提高語句的效率
select name ,(case address when '北京' then '一線城市' when '上海' then '一線城市' end) as '工作城市' from emp; -- 根據成績劃分等級 select id ,name ,(case when math >= 85 then '優秀' when math >= 60 then '及格' else '不及格' end) '數學',(case when english >= 85 then '優秀' when englise >= 60 then '及格' else '不及格' end) '英語',(case when chinese >= 85 then '優秀' when chinese >= 60 then '及格' else '不及格' end) '語文' from emp;約束
概念:約束是作用于表中字段的規則,用于限制在表中的字段數據
目的:保證數據庫中數據的正確性,有效性和完整性
| 非空約束 | not null ,auto_increment | 限制該字段不能為空 |
| 唯一約束 | unique | 保證該數據在該字段中都是唯一的 |
| 主鍵約束 | primary key | 主鍵是唯一的標識,要求非空且唯一 |
| 默認約束 | default | 保存數據時,如果沒指定數值,則采用默認值來保存 |
| 檢查約束(8.0.16)版本之后 | check() | 保證某一字段的數據滿足某個條件 |
| 外鍵約束 | forigen | 用于建立兩張表之間的聯系**,保證數據的一致性和完整性** |
外鍵約束
概念:如果用兩張表的數據建立連接,從而保證數據的一致性和完整性
create table [表名]( [字段名] 數據類型,...-- 一定要先創建外鍵字段,才可以指定這個字段為外鍵[constraint] [外鍵名稱] foreign key [外鍵字段名] references [主表](主表的列名); )-- 第二種 alter table [表名] add constraint [外鍵名稱] foreign key [外鍵字段名] references [主表](主表的列名);-- 刪處外鍵 alter table emp drop foreign key [外鍵名稱] create table emp ( id int auto_increment PRIMARY KEY comment '員工id', name varchar(20) not NULL comment '員工姓名', age int comment'年齡', job VARCHAR(20) comment '職責', salary int comment '薪資', entrydate date comment '入職時間', manager_id int not null comment '直屬領導id', dept_id int COMMENT '部門id', constraint id FOREIGN key (dept_id) references dept(id) )comment '員工表';多表查詢
多表關系
項目開發過程中,在進行數據庫表結構設計時,會根據業務需求及業務模塊之間的關系,分析并設計表結構,由于業務之間的互相關聯,表之間有以下關系:一對多,多對多,一對一
多的一方添加外鍵,多對多,則可以建立新的表,含量有兩方的主鍵
一對一
案例:用戶與用戶之間的詳情關系
關系:一對一關系,多用于單表的拆分,將一張表的基礎字段放在一張表中,其他詳情放在有另一張表中,以提升操作效率
實現:在任意一方加入外鍵,關聯另一方的主鍵,并設置外鍵為唯一的
多表查詢概述
笛卡爾積:select * from emp,dept;
select * from emp ,dept where dept.id = emp.id;內連接
概念:相當于查詢 兩個表之間的交集部分
隱式內連接
select [字段列表] from 表1,表2 where 條件; -- 實例,取別名 select * from emp ,dept d where d.id = emp.id;顯示內連接
select [字段列表] from 表1 inner join 表2 on 連接條件...; -- 實例 select e.name ,d.name from emp e inner join dept d on e.id = d.id;外連接
概念:如下
左外連接:查詢左表的全部數據以及兩表之間的交集數據
select [字段列表] from 表1 left outer join 表2 on 條件...; -- 示例 select e.name ,d.name from emp e left outer join dept d on e.id = d.id;右外連接:查詢右表所有的數據以及兩表之間的交集數據
select [字段列表] from 表1 right outer join 表2 on 條件...; -- 示例,不管你字段中 select e.name ,d.* from emp e right outer join dept d on e.id = d.id;自連接
概念:當前表與自身的連接查詢,自連接必須使用表別名。
聯合查詢
概念:對于union查詢,就是把多次查詢的結果合并起來,形成一個新的查詢結構,并集結果集
注意:這兩個表的結構必須相同(列數,字段類型保持一致)
select [字段列表] from 表1... union [all] -- all 就是會把默認去掉的重復記錄加上, select [字段列表] from 表2...; -- 示例 select * from emp where age >=50 union all select * from emp where salary >= 8000;子查詢
概念:sql語句中嵌套select語句,稱為嵌套語句,又稱子查詢
select * from 表1 where column1 = (select column1 from 表2);根據查詢結果的不同,可分為以下幾種
- 標量子查詢
- 列子查詢(子查詢結果為一列)
- 行子查詢(子查詢結果為一行)
- 表子查詢(子查詢結果為多行多列)
根據子查詢的位置:分為,where 之后 ,from 之后, select 之后;
標量子查詢
-- 示例 select * from emp where dept_id = (select id from dept where name = '銷售部'); -- 查詢在東方白入職之后的員工信息 select * from emp where entryDate > (select entryDate from emp where name = '東方白');列子查詢
子查詢的返回結果時一列可以是多列,做為結果銜接主句,這種稱為列子查詢
常用的操作符:in,not in ,any ,some,all
| in | 在指定的集合范圍之內多選一 |
| not in | 不在指定的集合范圍內 |
| any | 子查詢列表中,有任意一個滿足即可 |
| some | 等同于 any |
| all | 子查詢的返回列表的所有值都必須滿足 |
行子查詢
子查詢返回的結果是一行多行。
常用操作符:= , <> ,in,not in
-- 示例 查詢'張無忌'的薪資和直屬領導一致的員工信息,子查詢所返回的結果是多個字段 select * from emp where (salary ,manager_id) = (select salary ,manager_id from emp where name = '張無忌');表子查詢
銜接在from 后的子查詢,將子查詢的結果當成一個新的表,在進行篩選
-- 示例 ,在from 之后的子查詢,子查詢的結果當成一個表然后進行連接查詢 select e.* ,d.* from (select * from emp where entryDate > '2006-10-2') e left join dept d on dept_id = d.id;多表查詢案例
創建表的語句:
create table salgrade( grade int , losal int , hisal int )comment '薪資等級表';insert into salgrade values (1,0,3000); insert into salgrade values(2,3001,5000); insert into salgrade values(3,5001,8000); insert into salgrade values(4,8001,10000); insert into salgrade values(5,10001,15000); insert into salgrade values(6,15001,20000); insert into salgrade values(7,20001,25000); insert into salgrade values(8,25001,35000); insert into salgrade values(9,35001,45000);insert into salgrade VALUES(1,0,5000); insert into salgrade VALUES(2,0,8000); insert into salgrade VALUES(3,0,15000); insert into salgrade VALUES(4,0,10000); insert into salgrade VALUES(5,0,15000); insert into salgrade VALUES(6,0,20000); insert into salgrade VALUES(7,0,25000); insert into salgrade VALUES(8,0,3000); insert into salgrade VALUES(9,0,3000); insert into salgrade VALUES(10,0,30000);select * from salgrade;create table dept( d int auto_increment PRIMARY KEY comment '部門id', name VARCHAR(20) COMMENT '部門名稱' )comment '部門表';-- alter table [表名] change [舊字段名 數據類型(長度)] ; alter table dept CHANGE d id int ;select * from dept;insert into dept values (1,'財務部門'); insert into dept values (2,'研發部門'); insert into dept values (4,'銷售部門'); insert into dept values (3,'法律部門');create table emp ( id int auto_increment PRIMARY KEY comment '員工id', name varchar(20) not NULL comment '員工姓名', age int comment'年齡', job VARCHAR(20) comment '職責', salary int comment '薪資', entrydate date comment '入職時間', manager_id int not null comment '直屬領導id', dept_id int COMMENT '部門id', constraint id FOREIGN key (dept_id) references dept(id) )comment '員工表';insert into emp VALUES(1,'潘勝志',19,'軟件設計師',18000,'2001-10-12',1,2); insert into emp VALUES(2,'擦痕',19,'法律顧問師',18000,'2002-10-12',1,4); insert into emp VALUES(12,'李章',19,'法律顧問師',10000,'2002-10-12',1,4); insert into emp VALUES(3,'陳悅',20,'數據庫維護',18000,'2004-10-12',1,2); insert into emp VALUES(4,'徐宏都',129,'java開發工程師',18000,'2001-10-12',1,2); insert into emp VALUES(5,'周志銳',77,'銷售部組長',18000,'2021-10-12',1,3); insert into emp VALUES(6,'臣下',55,'會計',18000,'2011-10-12',1,1); insert into emp VALUES(7,'豫章',44,'研發部分析師',18000,'2014-10-12',1,2); insert into emp VALUES(8,'李志濤和',19,'網絡工程師',18000,'2001-10-12',1,2); insert into emp VALUES(9,'里博維',29,'銷售部經理',18000,'2021-10-12',1,3); insert into emp VALUES(10,'神采房',39,'嵌入式開發工程師',18000,'2001-10-12',1,2); insert into emp VALUES(11,'與張詩也',69,'會計會長',18000,'2016-10-12',1,1); insert into emp VALUES(13,'與張詩也',59,'會計會長',17000,'2012-10-12',1,null); insert into emp VALUES(14,'與張詩也',39,'會計會長',18000,'2016-10-12',1,null );案例實操:
-- 查詢員工的姓名年齡,職位,部門信息 select ename,work,dept from emp inner join dept on dept_id = dept.id; -- 隱式鏈接 select emp.name,age,job,dept.name from emp,dept where emp.dept_id = dept.id; -- 顯示連接,查詢員工年齡小于30的姓名,工作,部門名稱, select emp.name ,emp.age,job,dept.name from emp inner join dept on dept_id = dept.id where age < 30; -- 查詢擁有員工的部門id ,和部門名稱,并去重 select diatinct dept_id,dept.name from emp inner join dept on dept_id = dept.id; -- 查詢所有年齡大于40歲的員工,及其歸屬的部門名稱,如果員沒有份配部門也展示出來,左外連接如下 select e.*,d.name from emp e LEFT JOIN dept d on dept_id = d.id where age > 40; -- 查詢所有員工的工資等級,并按等級排序,這個等級是沒有主外鍵 between and 也可以 SELECT e.*,s.* from emp e ,salgrade s where salary >= s.losal and salary <= s.hisal order by s.grade DESC; -- 查詢員工研發部的信息以及工資等級, -- 第一種實現方法,連接了兩個表,但不能出現dept表的信息 SELECT e.*,s.grade from emp e ,salgrade s where salary >= s.losal and salary <= s.hisal and dept_id = (select id from dept where dept.name = '研發部門') order by s.grade DESC; -- 第二種實現方法 SELECT e.*,s.grade,d.* from emp e ,salgrade s,dept d where salary >= s.losal and salary <= s.hisal and d.id = dept_id and d.name = '研發部門' order by s.grade DESC ; -- 查詢研發部員工的平均薪資 select avg(e.salary)as middleMoney from emp e LEFT JOIN dept d on e.dept_id = d.id where d.name = '研發部門'; -- 查詢員工比潘勝志薪資高的員工信息 select * from emp where salary > (select salary from emp where name = '潘勝志'); -- 查詢比平均工資高的員工信息 select * from emp where salary > (select avg(salary) from emp); -- 查詢低于研發部門平均工資的員工 select * from emp where salary < (select avg(salary) from emp,dept where dept_id = dept.id and dept.id = 1 ); -- 查詢研發部門的員工低于本部平均薪資的所有部門對應的員工信息 select * from emp e2 where e2.salary < (select avg(salary) from emp e1 where e2.dept_id = e1.dept_id); -- 驗證 select *,(select avg(salary) from emp,dept where dept_id = dept.id and dept.name = '研發部門' ) '平均薪資' from emp e2 where e2.salary < (select avg(salary) from emp,dept where dept_id = dept.id and dept.name = '研發部門' ); -- 查看平均工資對比驗證 select * ,(select avg(salary) from emp e1 where e1.dept_id = e2.dept_id) '平均薪資' from emp e2 where e2.salary < (select avg(salary) from emp e1 where e1.dept_id = e2.dept_id); -- 查詢部門的所有信息,并統計員工的人數 select d.id ,d.name,(select count(*) from emp e where dept_id = d.id) '人數' from dept d; -- 第二種,先連成一張整體表,在分組排序 select dept.name, count(dept_id) as '人數' from emp,dept where dept_id = dept.id group by dept_id; -- 與第二種一致 select dept.name,count(dept.name), dept_id as '人數' from emp,dept where dept_id = dept.id group by dept.name; -- 查詢所有學生選課情況,顯示學生名稱,學號,課程名稱-- 用大量數據測試一下查詢效率事務
事務理解:事務是一組操作的集合,他是一個不可分割的單位,十五會把所有的操作作偽一個整體,一起向系統提交或者撤銷操作,請求,這些操作要么成功,要么失敗,保證數據的完整性和一致性
開啟事務 ----> 出現異常 -----> 回滾事務(拋異常) -------> 問題解決-----> 提交事務
例子: A賬號 B賬戶
A賬戶 ----> 500元----->B賬戶
\1. A賬戶劃去500元 –> update table set account = xxx where Id = A賬戶 id 運行后1,出現異常,可以中斷,數據不會發生變化,可以回管道之前的狀態
\2. B賬戶增加500元 ->
\3. 要么成功,要么失敗
-- 開啟事務 start transaction 或者 begin; -- 設置自動提交關閉 set autocommit = 0; -- 出錯,回滾事務 rollback; -- 數據正確,未發生異常,提交數據 commit;事物的四大特性:(ACID)
原子性( atomicity ): 事務是不可分割的最小單元,要么全部成功,要么全部失敗
一致性(consistency):事務完成時,必須保證所有的數據一致
隔離性(isolation):數據庫系統提供的隔離機制,保證事務在不受外部并發操作的獨立環境下運行,多個事務相互隔離,在各自獨立的環境下運行
持久性(Durability):事務一旦提交或者回滾,他對數據庫中的數據的改變是永久的
并發事務所引發的問題
| 臟讀 | 讀臟讀錯了,亂作一團 |
| 幻讀 | 插不進去,或者插錯了 |
| 不可重復讀 | 不能插入重復的數據 |
詳細見下解答
隔離級別
| read uncommitted | 有 | 有 | 有 |
| read committed(orcale ,默認級別) | 無 | 有 | 有 |
| repeatable read (數據庫默認級別) | 無 | 無 | 有 |
| serializable | 無 | 無 | 無 |
事務的隔離級別(由低到高,性能由高到低)
數據庫常隔離用命令
-在隔離級別中常用的命令 -設置關閉自動提交 set autocommit = 0; -開啟事務命令 start transaction ; -查詢事務級別-5.7版本以前 select @@tx_isolation ; show variables like 'tx_isolation'; -查詢事務級別5.7以后; select @@tx_isolation ; show variables like 'tx_isolation'; -- 修改給力級別命令,只是對當前會話窗口有效 set session transaction isolation level read uncommitted; set session transaction isolation level read committed; set session transaction isolation level REPEATABLE READ; set session transaction isolation level serializable; -- 修改給力級別命令,針對所有客戶端窗口有效 set global transaction isolation level REPEATABLE READ; -其次便是增刪改查命令,查看表結構等 ......- 臟讀:執行SQL,就直接全局修改,回滾也不會改變數據
- 不可重復讀:在一個sql會話中,沒有commit ,所查詢的數據永遠是剛開始的那個表的,盡管其他會話修改了數據
- 幻讀:在一個會話中,數據庫的表被其添加了數據(id = 5 )并提交后,在另一個會話中查詢該插入的數據顯示為空,但在這個會話中插入(id = 5)的語句時就會出現,重復提交id= 5 的數據,進而出現了串行化限制他們進行排隊。
讀未提交 等級 1
-read uncommitted
解釋:在關閉自動提交事務的情況下,在執行操縱數據庫時,運行完數據庫語句后,它會直接修改表中的數據,也就是只讀了數據,但還沒commit,就可以查出修改后的數據。這肯定會出現很多數據異常問題。
Ps 其中123步都是開啟事務必備操作
\1. 先將默認的隔離等級設置為 讀未提交。
-隔離命令:- set session transaction isolation level read uncommitted ;
\2. 將默認的自動提交關閉 -set autocommit = 0 ;
\3. 其次開啟事務 – start transaction ;
\4. 此時做修改時或者插入(CRUD)時,操作者未提交 -commit 數據也會被加載入數據庫,但此時操作者又可以回滾,回滾后數據與之前的數據不一致,在這一段時間里,如果利用該數據去操作相關事件,會導致回滾后的數據與之前的數據不一致。數據失常。
\5. 所以后續出現了-讀已提交機制
讀已提交 等級 2
-read committed:
解釋:當操作者修改表數據后,如果沒有提交 -commit ; 則不會將數據加載到數據庫中,防止讀臟數據
-read committed,操作只會在當前的會話中有效,只有等提交后才全局有效
Ps
\1. 在關閉自動提交的基礎上設置隔離級別 – set session transaction isolation level read committed ;
\2. 當修給數據庫信息時 – update user set account = ‘ 潘勝志 ’ where id = 1; 未提交數據 – commit ; ,則不會將數據修改入數據庫文件。
\3. 提交 – commit ; 后才可以查詢得到修改的信息。
可重復讀 等級4
-repeattable Read :
非幻讀:在一個會話中,即一個數據操縱過程中沒有提交,你查詢的數據庫數據與你每次查詢的數據都是一致的,反之亦然。
解釋:可重復讀它是在讀已提交的隔離級別上,增加了防止幻讀的功能。即在你修改 -– update user set account = ‘ 潘勝志 ’ where id = 1; 修改數據方和查詢數據方都提交數據 – commit ;時,查詢放數據才會查出修改的情況。當有任何一方未提交,查詢的數據任然是你上一次查詢的結果。
Ps
\1. 在關閉自動提交的基礎上,修改隔離級別
-set session transaction isolation level REPEATTABLE READ;
串行化隔離 等級8
Ps
\1. 在開啟事務的基礎上,修改隔離級別
-set session transaction isolation level serizabble
\2. 當你在里另一個窗口修改數據庫表時,會禁止其他窗口修改數據表,會阻塞其他的命令過程。
\3. 當其他事務提交后,才會允許其他窗口運行操縱語句
數據庫進階
存儲引擎
索引
sql優化
視圖/存儲過程/觸發器
鎖
innoDB引擎
mysql 管理
總結
以上是生活随笔為你收集整理的mysql数据库,语法语句总结。以及事务理解-基础篇的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js实现京东秒杀
- 下一篇: oracle数据库用户的删改查