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