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