MySQL零基礎入門視頻課程——筆記

視頻課程鏈接:http://edu.51cto.com/course/15968.html

MySQL,主講:湯小洋

一、MySQL簡介

1. 介紹

1.1 什麼是數據庫?

​ 數據庫:Database,按照數據結構來組織、存儲和管理數據的倉庫,簡單來說就是存儲數據的倉庫

​ 數據庫管理系統:用來管理數據庫的軟件系統,常見:MySQL、Oracle、SQL Server、DB2、Sybase、Access等

1.2 什麼是MySQL?

​ MySQL:是一個開源的關係型數據庫管理系統,由瑞典MySQL AB公司開發,後來被Oracle收購,所以目前屬於Oracle公司

​ 特點:體積小、速度快、成本低、開源,中小型網站都使用MySQL數據庫

​ 版本:企業版Enterprise、社區版Community

​ DBA:Database Administrator 數據庫管理員

2. 安裝MySQL

2.1 版本

​ 分平臺:Windows、Linux、Mac

​ 分版本:5.x 6.x 7.x 8.x

2.2 安裝

​ 安裝位置:/usr/local/mysql

  • bin 可執行文件
  • data 數據庫文件
  • my.cnf 核心配置文件

2.3 服務

​ 安裝MySQL後,會在操作系統中添加一個MySQL服務

​ 需要先啓動服務才能使用MySQL:

  • 系統偏好設置——>MySQL

  • 勾選Automatically Start MySQL Server on Startup,設置開機自動啓動MySQL服務

二、基本操作

1. 連接MySQL

​ 語法:

mysql -u 用戶名 -p密碼 -h 數據庫服務器地址 -D 數據庫名

​ 安裝MySQL以後,默認有一個管理員 root

2. 查看數據庫和表

show databases;  -- 查看當前所有數據庫
use 數據庫名; -- 切換數據庫
show tables; -- 查看當前數據庫中所有表
select database();  -- 顯示當前操作的數據庫
select user();  -- 顯示當前登陸的用戶

​ mysql庫是系統庫,包含MySQL的相關係統信息,不要修改

3. 導入初始數據

3.1 導入數據

​ 以.sql結尾的文件是數據庫腳本文件

​ 先連接登陸MySQL,然後執行如下命令:

source /Users/appleuser/Desktop/init.sql

3.2 表結構

desc 表名;   -- 查看錶的結構
select * from 表名; -- 查看錶中的所有數據

emp僱員表

列名 類型 含義
empno int 整數 僱員編號
ename varchar 字符串 僱員姓名
job varchar 字符串 工作、職位
mgr int 整數 上司/領導的編號
hiredate date 日期 入職時間
sal double 小數 薪水、工資
comm int 整數 獎金
deptno int 整數 部門編號

dept部門表

列名 類型 含義
deptno int 整數 部門編號
dname varchar 字符串 部門名稱
loc varcher 字符串 部門位置

salgrade工資等級表

列名 類型 含義
grade int 整數 等級編號
losal int 整數 工資下限
hisal int 整數 工資上限

bonus獎金錶

三、SQL

​ SQL:Structured Query Language 結構化查詢語言,用來對數據庫進行查詢、更新和管理的一種特殊的語言

​ 包含三個部分:

  • DML

    Data Manipulation Language 數據操作語言

    用於檢索或更新數據庫:insert delete update select 增刪改查

  • DDL

    Data Definition Language 數據定義語言

    用於定義數據的結構:create alter drop

  • DCL

    Data Control Language 數據控制語言

    用於定義數據庫用戶的權限:grant revoke

四、 查詢操作

1. 簡介

1.1 語法

select 列名1 別名1,列名2 別名2... from 表名;

示例:

select ename from emp;
select ename,job,hiredate from emp;
select * from emp;
select ename 姓名,job 職位,hiredate 入職時間 from emp;
select empno,ename,sal "your salary" from emp;  -- 別名包含空格時,需要使用雙引號引起來

1.2 用法

  • 字符串連接concat()

    select concat('編號爲',empno,'的僱員,姓名爲',ename,',職位爲',job) from emp;
  • 四則運算 + - * %

    例:查詢僱員姓名及年薪

    select ename 僱員姓名,sal*12 年薪 from emp;
    select ename 僱員姓名,(sal+comm)*12 年薪 from emp;  -- 有問題的
    select ename 僱員姓名,(sal+ifnull(comm,0))*12 年薪 from emp;  -- 使用ifnull()

    在MySQL中,NULL與任何值進行運算,結果都爲NULL

  • 去除重複列 distinct

    例:查詢所有的職位

    select distinct job from emp;
    select ename,job from emp; -- 在去除重複列時只有當所有列都相同時才能去除

2. 限定查詢

​ 語法:

select 列名1 別名1,列名2 別名2... 
from 表名 
where 條件;

2.1 比較運算符

> < >= <= = !=或<>

​ 例:查詢工資大於1500的僱員信息

select * from emp where sal>1500;

​ 例:查詢僱員編號不是7369的僱員信息

select * from emp where empno!=7369;

​ 例:查詢姓名是smith的僱員編號、姓名、工資、入職時間

select empno,ename,sal,hiredate from emp where ename='smith';

注:字符串要使用引號引起來,同時MySQL中不區分大小寫

2.2 null 或 not null

​ 例:查詢沒有獎金的僱員信息

select * from emp where comm is null;
select * from emp where comm is not null;

注:判斷是否爲null時使用的是is,不能使用比較運算符=

2.3 and

​ 例:查詢基本工資大於1000,並且可以獲取獎金的僱員姓名、工資、獎金

select ename,sal,comm from emp where sal>1000 and comm is not null;

2.4 or

​ 例:查詢從事銷售工作,或工資大於等於2000的僱員信息

select * from emp where job='salesman' or sal>=2000; 

2.5 not

​ 例:查詢從事非銷售工作,並且工資不小於1500的僱員的編號、姓名、職位、工資、入職時間

select empno,ename,job,sal,hiredate from emp where job!='salesman' and sal >= 1500;
select empno,ename,job,sal,hiredate from emp where not (job='salesman' and sal<1500);  -- 有問題的
select empno,ename,job,sal,hiredate from emp where (not job='salesman') and (not sal<1500);

2.6 between and

​ 例:查詢基本工資大於1500,但小於3000的僱員信息

select * from emp where sal>1500 and sal<3000;
select * from emp where sal between 1500 and 3000;

​ 注:between and 包含臨界值

​ 例:查詢1981年入職的僱員編號、姓名、入職時間、所在部門編號

select empno,ename,hiredate,deptno from emp where hiredate between '1981-1-1' and '1981-12-31';

​ 注:日期必須使用引號引起來

2.7 in 或 not in

​ 例:查詢編號爲7369、7499、7788的僱員信息

select * from emp where empno=7369 or empno=7499 or empno=7788;
select * from emp where empno in (7369,7499,7788);

​ 例:查詢姓名爲smith、allen、king的僱員編號、姓名、入職時間

select empno,ename,hiredate from emp where ename in ('smith','allen','king');
select empno,ename,hiredate from emp where ename not in ('smith','allen','king');

2.8 like

​ 用來進行模糊查詢,需要結合通配符一起使用

​ 常用通配符:

  • % 可以匹配任意長度字符
  • _ 只能匹配單個字符

​ 例:查詢僱員姓名以S開頭的僱員信息

select * from emp where ename like 'S%';

​ 例:查詢僱員姓名中包含M的僱員信息

select * from emp where ename like '%M%';

​ 例:查詢從事銷售工作,並且姓名長度爲4個字符的僱員信息

select * from emp where job='salesman' and ename like '____';

​ 例:查詢1981年入職的僱員編號、姓名、入職時間、所在部門編號

select empno,ename,hiredate,deptno from emp where hiredate like '1981%';

3. 排序

3.1 語法

​ 語法:

select 列名1 別名1,列名2 別名2... 
from 表名 
where 條件
order by 排序列1 asc|desc,排序列2 asc|desc...;

​ asc表示升序,desc表示降序,省略時默認按升序

3.2 示例

​ 例:查詢所有僱員信息,按工資由低到高排序

select * from emp order by sal;

​ 例:查詢部門10的僱信息,按工資由高到低排序,如果工資相同,則按入職時間由早到晚排序

select * from emp where deptno=10 order by sal desc,hiredate;

​ 例:查詢僱員編號、姓名、年薪,按年薪由高到低排序

select empno,ename,(sal+ifnull(comm,0))*12 income from emp order by income desc;

五、多表查詢

1. 簡介

​ 同時從多張表中查詢數據,一般來說多張表之間都會存在某種關係

2. 基本用法

2.1 語法

select 列名1 別名1,列名2 別名2... 
from 表名1 別名1,表名2 別名2... 
where 條件
order by 排序列1 asc|desc,排序列2 asc|desc...;

​ 例:將emp表和dept表進行多表查詢(笛卡爾積)

select * from emp,dept;

​ 通過將兩張表的關聯字段進行比較,去掉笛卡爾積,多表查詢時一般都會存在某種關係

select * from emp,dept where emp.deptno=dept.deptno;

2.2 示例

​ 例:查詢僱員編號、僱員姓名、工資、所在部門名稱及位置(等值連接)

select empno,ename,sal,dname,loc
from emp e,dept d
where e.deptno=d.deptno;

​ 例:查詢僱員姓名、工資、入職時間、所在部門編號、部門名稱

select e.ename,e.sal,e.hiredate,d.deptno,d.dname
from emp e,dept d
where e.deptno=d.deptno;  -- 如果多張表中出現同名的列,當查詢時需要指定前綴

​ 例:查詢僱員姓名、僱員工資、領導姓名、領導工資(自身連接)

select e.ename 僱員姓名,e.sal 僱員工資,m.ename 領導姓名,m.sal 領導工資
from emp e,emp m
where e.mgr=m.empno;

​ 例:查詢僱員姓名、僱員工資、部門名稱、領導姓名、領導工資

select e.ename 僱員姓名,e.sal 僱員工資,d.dname 部門名稱,m.ename 領導姓名,m.sal 領導工資
from emp e,dept d,emp m
where e.deptno=d.deptno and e.mgr=m.empno;

​ 例:查詢僱員姓名、僱員工資、部門名稱、工資所在等級(非等值連接)

select e.ename 僱員姓名,e.sal 僱員工資,d.dname 部門名稱,s.grade 工資等級
from emp e,dept d,salgrade s
where e.deptno=d.deptno and e.sal between s.losal and s.hisal;

​ 例:查詢僱員姓名、僱員工資、部門名稱、僱員工資等級、領導姓名、領導工資、領導工資等級

select e.ename 僱員姓名,e.sal 僱員工資,d.dname 部門名稱,s.grade 僱員工資等級,m.ename 領導姓名,m.sal 領導工資,sm.grade 領導工資等級
from emp e,dept d,salgrade s,emp m,salgrade sm
where e.deptno=d.deptno and e.sal between s.losal and s.hisal and e.mgr=m.empno and m.sal between sm.losal and sm.hisal;

3. SQL99標準

3.1 簡介

​ SQL99標準,也稱爲SQL1999標準,是1999年制定的

​ 分類:內連接、外連接

3.2 內連接

​ 使用inner join…on

​ 語法:

select 列名1 別名1,列名2 別名2... 
from 表名1 別名1 inner join 表名2 別名2 on 多表間的關聯關係
where 條件
order by 排序列1 asc|desc,排序列2 asc|desc...;

​ 例:查詢僱員編號、僱員姓名、工資、部門名稱

select e.empno,e.ename,e.sal,d.dname
from emp e inner join dept d on e.deptno=d.deptno;

​ 例:查詢工資大於1500的僱員姓名、工資、部門名稱、領導姓名

select e.ename,e.sal,d.dname,m.ename
from emp e inner join dept d on e.deptno=d.deptno inner join emp m on e.mgr=m.empno
where e.sal>1500;
select e.ename,e.sal,d.dname,m.ename
from emp e,dept d,emp m
where e.deptno=d.deptno and e.mgr=m.empno and e.sal>1500;

3.3 外連接

​ 分類:

  • 左外連接 left outer join…on,也稱爲左連接left join…on

    以左邊的表作爲主表,無論如何都會顯示主表中的所有數據

  • 右外連接 right outer join…on,也稱爲右連接right join…on

    以右邊的表作爲主表,無論如何都會顯示主表中的所有數據

​ 語法:

select 列名1 別名1,列名2 別名2... 
from 表名1 別名1 left join 表名2 別名2 on 多表間的關聯關係
where 條件
order by 排序列1 asc|desc,排序列2 asc|desc...;

​ 例:查詢僱員姓名、工資、領導姓名、領導工資(有的僱員沒有領導)

select e.ename,e.sal,m.ename,m.sal
from emp e,emp m
where e.mgr=m.empno;  -- 有問題的
select e.ename,e.sal,m.ename,m.sal
from emp e inner join emp m on e.mgr=m.empno;  -- 有問題的
select e.ename,e.sal,m.ename,m.sal
from emp e left join emp m on e.mgr=m.empno;
select e.ename,e.sal,m.ename,m.sal
from emp m right join emp e on e.mgr=m.empno;

​ 例:查詢部門編號、部門名稱、部門位置、部門中僱員姓名、工資

select d.deptno,d.dname,d.loc,e.ename,e.sal
from dept d left join emp e on d.deptno=e.deptno
order by d.deptno;

六、聚合函數和分組統計

1. 聚合函數

​ 聚合函數,稱爲統計函數

​ 常用函數函數:

  • count() 總數量
  • max() 最大值
  • min() 最小值
  • sum() 和
  • avg() 平均值

​ 例:查詢部門30的總人數

select count(empno) 總人數 from emp where deptno=30;
select max(sal) from emp;
select ename 僱員姓名,avg(sal) 平均工資 from emp where deptno=10;  -- 不合理

注:聚合函數在統計時會忽略NULL值

​ 例:查詢部門30的最高工資、最低工資、平均工資

select max(sal),min(sal),round(avg(sal),2) from emp where deptno=30;

2. 分組統計

2.1 語法

select 列名1 別名1,列名2 別名2... 
from 表名1 別名1 left join 表名2 別名2 on 多表間的關聯關係
where 分組前的條件
group by 分組列
having 分組後的條件
order by 排序列1 asc|desc,排序列2 asc|desc...;

2.2 示例

​ 例:查詢每個部門的平均工資

select deptno 部門編號,avg(sal) 平均工資
from emp
group by deptno;
select d.dname 部門名稱,avg(sal) 平均工資
from emp e,dept d
where e.deptno=d.deptno
group by d.dname;

​ 注:

  • 在MySQL中分組統計時可以查詢出分組列以外的其他列,而在Oracle中不行
  • 建議將要查詢出的列作爲分組列

​ 例:查詢部門的名稱及每個部門的員工數量

select d.dname 部門名稱,count(e.empno) 員工數量
from dept d left join emp e on d.deptno=e.deptno
group by d.dname;

​ 例:查詢平均工資大於2000的部門的編號和平均工資

select deptno,avg(sal)
from emp
group by deptno
having avg(sal)>2000;

​ 例:查詢出非銷售人員的職位名稱,以及從事同一工作的僱員的月工資總和,並且要滿足工資總和大於5000,查詢的結果按月工資總和的升序排列

select job,sum(sal) sum
from emp
where job!='salesman'
group by job
having sum(sal)>5000
order by sum;

​ 例:查詢部門平均工資的最大值

select max(avg(sal))
from emp
group by deptno;  -- MySQL中不支持

​ 注:在MySQL中聚合函數不能嵌套使用,而Oracle中可以

select max(temp.avg)
from (select avg(sal) avg from emp group by deptno) temp;

七、子查詢

1. 簡介

​ 一個查詢中嵌套着另一個查詢,稱爲子查詢

  • 子查詢必須放在小括號中
  • 子查詢可以出現在任意位置,如select、from、where、having等

2. 基本用法

2.1 語法

select (子查詢)
from (子查詢) 別名
where (子查詢)
group by 
having (子查詢)

2.2 示例

​ 例:查詢工資比7566高僱員信息

-- 使用多表連接
select e2.*,e1.ename,e1.sal
from emp e1,emp e2 
where e1.empno=7566 and e2.sal>e1.sal;
-- 使用子查詢
select sal from emp where empno=7566;
select * from emp where sal> (select sal from emp where empno=7566);

​ 例:查詢工資比部門30員工的工資高的僱員信息

select sal from emp where deptno=30;
select * from emp where sal>(select sal from emp where deptno=30); -- 錯誤用戶

注:將子查詢與比較運算符一起使用時,必須保證子查詢返回的結果不能多於一個

​ 例:查詢僱員的編號、姓名、部門名稱

-- 使用多表連接
select e.empno,e.ename,d.dname from emp e,dept d where e.deptno=d.deptno;
-- 子查詢
select empno,ename,(select dname from dept where deptno=e.deptno) from emp e;

​ 總結:

  • 一般來說,多表連接查詢都可以使用子查詢替換,但有的子查詢不能使用多表連接查詢來替換
  • 子查詢特點:靈活、方便,一般常作爲增、刪、改、查操作的條件,適合於操作一個表的數據
  • 多表連接查詢更適合於查看多表中數據

3. 子查詢分類

​ 可以分爲三類:

  • 單列子查詢

    返回單行單列,使用頻率最高

  • 多行子查詢

    返回多行單列

  • 多列子查詢

    返回單行多列或多行多列

3.1 單列子查詢

​ 例:查詢工資比7654高,同時又與7900從事相同工作的僱員信息

select *
from emp
where sal>(
    select sal from emp where empno=7654
) and job=(
    select job from emp where empno=7900
);

​ 例:查詢工資最低的僱員的姓名、工作、工資

select ename,job,sal from emp where sal=(select min(sal) from emp);

​ 例:查詢工資高於公司平均工資的僱員信息

select * from emp where sal>(select avg(sal) from emp);

​ 例:查詢每個部門的編號和最低工資,要求最低工資大於等於部門30的最低工資

select deptno,min(sal)
from emp
group by deptno
having min(sal)>=(
    select min(sal) from emp where deptno=30
);

​ 例:查詢部門的名稱、部門的員工數、部門的平均工資、部門的最低收入僱員的姓名

-- 拆分
select deptno,count(empno),avg(sal),min(sal)
from emp
group by deptno;
-- 方式1:使用子查詢
select 
    (select dname from dept where deptno=e.deptno) dname,
    count(empno),
    avg(sal),
    (select ename from emp where sal=min(e.sal)) ename
from emp e
group by deptno;
-- 方式2:使用多表連接查詢
select d.dname,t.count,t.avg,e.ename
from (select deptno,count(empno) count,avg(sal) avg,min(sal) min from emp group by deptno) t,dept d,emp e
where d.deptno=t.deptno and e.sal=t.min;

​ 例:查詢平均工資最低的工作及平均工資

-- 拆分
select min(t.avg) 
from  (
  select avg(sal) avg from emp group by job
) t;

select job,avg(sal)
from emp
group by job
having avg(sal) = (
    select min(t.avg) from  (select avg(sal) avg from emp group by job) t
);

3.2 多行子查詢

​ 對於多行子查詢,可以使用如下三種操作符:

  • in

    例:查詢所在部門編號大於等於20的僱員信息

    select * from emp where deptno>=20;
    select * from emp where deptno in (
    select deptno from dept where deptno>=20
    );

    例:查詢工資與部門20中的任意員工相同的僱員信息se

    select * from emp where sal in (
    select sal from emp where deptno=20
    );  
  • any

    三種用法:

    =any:與任意一個相同,此時與in操作符功能一樣
    >any:只要比裏面最小的值大即可
    <any:只要比裏面最大的值小即可
    select * from emp where sal <any (
    select sal from emp where deptno=20
    );  
  • all

    兩種用法:

    >all:比裏面最大的值要大
    <all:比裏面最小的值要小
    select * from emp where sal <all (
    select sal from emp where deptno=20
    );  

3.3 多列子查詢

​ 多列子查詢一般出現在from子句中,作爲查詢結果集

​ 例:在所在從事銷售工作的僱員中找出工資大於1500的員工

select *
from (
    select * from emp where job='salesman'
) t
where t.sal>1500;

八、分頁查詢

1. limit關鍵字

​ 用來限制查詢返回的記錄數

​ 語法:

select 列名1 別名1,列名2 別名2... 
from 表名1 別名1 left join 表名2 別名2 on 多表間的關聯關係
where 分組前的條件
group by 分組列
having 分組後的條件
order by 排序列1 asc|desc,排序列2 asc|desc...
limit [參數1,]參數2

​ 可以接收一個或兩個數字:

  • 參數1用來指定起始行的索引,索引從0開始,即第一行的索引爲0
  • 參數2用來指定返回的記錄數量

​ 例:查詢工資的前3名

select * from emp order by sal desc limit 0,3;
select * from emp order by sal desc limit 3; -- 如果省略參數1,則默認爲0,即從第1條開始返回
例:查詢工資大於1000的第4-8個用戶
select * from emp where sal>1000 limit 3,5;

​ 例:查詢工資最低的用戶

select * from emp order by sal limit 1;

2. 分頁

​ 例:每頁顯示4條(pageSize每頁大小),顯示第3頁的內容(pageIndex頁碼)

select * from emp limit (pageIndex-1)*pageSize,pageSize  -- 計算
select * from emp limit (3-1)*4,4 -- 不能直接執行

​ 注:在MySQL中limit後面的參數不能包含任何運算,實際開發中都是在編程語言中進行計算,然後將結果發送給數據庫執行

九、常用函數

1. 字符串函數

  • concat(s1,s2,s3….) 拼接字符串

    select concat('aa','bb','cc')
    select concat('aa','bb','cc') from dual;
    select concat('編號爲',empno,'的員工,姓名爲',ename) from emp;

    注:dual表是MySQL提供的一張虛擬表,主要是爲了滿足select...from...語法習慣,一般測試時使用,無實際意義

  • lower(s) 將字符串變爲小寫select lower('Hello') from dual

  • upper(s) 將字符中變爲大寫select upper('Hello') from dual

  • length(s) 獲取字符串的長度select length('hello') from dual

  • reverse(s) 將字符串反轉select reverse('hello') from dual

  • trim(s) 去除字符串兩邊的空格select trim(' hello ') from dual,還有ltrim()和rtrim(),去除左邊或右邊的空格

  • replace(s,s1,s2) 將字符串s中的s1替換爲s2select replace('hello world','o','xx') from dual

  • repeat(s,n) 將字符串s重複n次後返回select repeat('hello',3) from dual

  • lpad(s,len,s1) 在字符串s的左邊使用s1進行填充,直至長度爲lenselect lpad('hello',8,'x') from dual

  • rpad(s,len,s1) 在字符串s的右邊使用s1進行填充,直至長度爲lenselect rpad('hello',8,'x') from dual

  • substr(s,i,len) 從第i個位置開始對字符串s進行截取,截取len個select substr('hello',2,3) from dual

2. 數值函數

  • ceil(n) 返回大於n的最小整數select ceil(10.1) from dual
  • floor(n) 返回小於n的最大整數select floor(10.1) from dual
  • round(n,y) 將n保留y位小數,四捨五入select round(3.1415,3) from dual
  • truncate(n,y) 將n保留y位小數,不四捨五入select truncate(3.1415,3) from dual
  • rand() 返回0到1的隨機數select rand() from dual

3. 日期和時間函數

  • now() 返回當前日期時間select now() from dual

  • curdate() 返回當前日期select curdate() from dual

  • curtime() 返回當前時間select curtime from dual

  • year(date) 返回日期中的年select year('2018-2-14') from dual

  • month(date) 返回日期中的月select month('2018-2-14') from dual

  • day(date) 返回日期中的日select day('2018-2-14') from dual

  • timestampdiff(interval,datetime1,datetime2) 返回兩個日期時間之間相隔的整數,單位由interval定義

    interval可取值:year、month、day、hour、minute、second

    select timestampdiff(day,'1993-9-23','2018-11-22') from dual

  • date_format(date,pattern) 格式化日期select date_format(now(),'%Y年%m月%d日 %H:%i:%s') from dual

    格式化參數:

    %Y 表示四位數字的年

    %m 表示兩位數字的月

    %d 表示兩位數字的日

    %H 表示兩位數字的小時,24小時制

    %i 表示兩位數字的分鐘

    %s 表示兩位數字的秒數

4. 流程控制函數

  • if(f,v1,v2) 如果f爲真,則返回v1,否則返回 v2 select if(5&gt;2,'yes','no') from dual

  • ifnull(v1,v2) 如果v1不爲null,則返回v1,否則返回v2select ifnull(null,'0') from dual

  • case when f1 then v1 when f2 then v2….else v end 如果f1爲真,則返回v1;如果f2爲真,則返回v2...否則返回v

    select case when 5>2 then 'yes' end from dual;
    select case when 5<2 then 'yes' else 'no' end from dual;
    select case when 5<2 then 'one' when 6>4 then 'two' else 'three' end from dual;

5. 系統信息函數

  • database() 返回當前操作的數據庫select database()
  • user() 返回當前登陸的用戶select user()
  • version() 返回MySQL服務器的版本select version()

十、更新操作

1. insert

​ 語法:

-- 語法1
insert into 表名 (列名1,列名2...) values (值1,值2...); 
-- 語法2:一次性插入多條數據
insert into 表名 (列名1,列名2...) values (值1,值2...),(值1,值2...),(值1,值2...)

​ 示例:

insert into dept (deptno,dname,loc) values (50,'市場部','南京');
insert into dept (deptno,dname) values (60,'開發部');
insert into dept values (70,'×××部','上海'); -- 如果是依次插入表中所有的列,此時可以省略列名
insert into dept values (11,'aaa','aaa'),(12,'bbb','bbb'),(13,'ccc','ccc');
insert into emp (empno,ename,job,hiredate,sal,deptno) values (9527,'唐伯虎','畫家',now(),6666,50);

2. delete

​ 語法:

delete from 表名 where 條件;

​ 示例:

delete from dept where deptno=60;
delete from dept where dname='×××部';
-- 刪除市場部所有工資高於5000的員工
select deptno from dept where dname='市場部'

delete from emp where deptno=(select deptno from dept where dname='市場部') and sal>5000;

​ 注::delete from emp會將表中所有數據都刪除

3. update

​ 語法:

update 表名 set 列名1=值1,列名2=值2... where 條件

​ 示例:

update dept set dname='market' where dname='市場部';
update emp set job='manager',sal=8888,comm=666 where ename='smith';

十一、表和庫的管理

1. 數據類型

​ 整數:smallint、int、bigint

​ 小數:float、double

​ 日期時間:date、time、datetime、timestamp

​ 字符串:varchar、char、text

​ 其他:clob 存儲文本大數據

      blob 存儲二進制大數據

2. 創建表

​ 語法:

create table 表名
(
    列名 數據類型 特徵,
    列名 數據類型 特徵,
    ....
    列名 數據類型 特徵
) charset=utf8;

​ 示例:

create table user
(
    id int,
    username varchar(20),
    password varchar(50)
);
create table t_student
(
    id int primary key auto_increment,  -- 將id作爲主鍵,自動增長,默認從1開始,每次遞增1
    name varchar(10) not null, -- 不允許爲空
    age int,
    sex varchar(8) not null default '女', -- 指定默認值
    address varchar(100),
    height double,
    birthday date
)charset=utf8;
insert into t_student (name,age,sex,birthday,height) values ('範婷婷',18,'女','1998-12-4',170.6);
insert into t_student (name,age,sex) values (null,10,'男');  
insert into t_student values (null,'程瑞',19,'男','南京',176.6,now());  

3. 修改表

  • 添加列

    語法:

    alter table 表名 add 列名 數據類型

    示例:

    alter table t_student add weight double;
  • 修改列類型

    語法:

    alter table 表名 modify 列名 數據類型

    示例:

    alter table t_student modify name varchar(250);
  • 修改列名

    alter table 表名 change 原列名 新列名 數據類型

    示例:

    alter table t_student change sex gender varchar(8);
  • 刪除列

    語法:

    alter table 表名 drop 列名

    示例:

    alter table t_student drop weight;
  • 修改表名

    語法:

    alter table 原表名 rename 新表名
    或
    rename table 原表名 to 新表名

    示例:

    alter table t_student rename student;
    rename table student to t_student;

4. 刪除表

​ 語法:

drop table 表名;
drop table if exists 表名;  

​ 示例:

drop table user;
drop table if exists user;

5. 截斷表

​ 清空表中的數據,作用類似於沒有條件的delete語句

​ 語法:

truncate table 表名;

​ delete與truncate區別:

  • delete會記錄日誌,所以速度慢,而truncate不記錄日誌,清空表並釋放資源,速度快
  • delete可以指定條件只刪除表中的部分數據,而truncate只能用來清空表中的所有數據
  • delete不會將自動增長列歸零,而truncate會

6. 創建庫

​ 語法:

create database 數據庫名 charset utf8;
create database if not exists 數據庫名 charset utf8;

​ 示例:

create database if not exists shop charset utf8;

7. 刪除庫

​ 語法:

drop database 數據庫名;
drop database if exists 數據庫名;

​ 示例:

drop database if exists shop;

十二、約束

1. 簡介

​ constraint約束是對錶中的數據的一種限制,保證數據的完整性和有效性

2. 約束分類

​ 有五種約束:

  • 主鍵約束 primary key

    用來唯一的標識一條記錄(數據),本身不能爲空

  • 唯一約束 unique

    不允許出現重複值

  • 檢查約束 check

    判斷數據是否符合指定條件

    注:MySQL會對check約束進行分析,但會忽略check約束,即不會強制執行此約束,可以通過SQL編程來解決

  • 非空約束 not null

    不允許爲null,但可以爲空字符串''

  • 外鍵約束 foreign key

    約束兩表之間的關聯關係

3. 添加約束

  • 方式1:在創建表時添加約束

    -- 約束沒有名稱
    create table student  -- 學生表
    (
    id int primary key,  -- 主鍵約束
        name varchar(10) not null,  -- 非空約束
        age int check(age between 1 and 120), -- 檢查約束
        sex varchar(8) not null check(sex in ('male','female')), -- 多種約束
        IDCard varchar(18) unique, -- 唯一約束
        class_id int, -- 外鍵列
        foreign key (class_id) references class(c_id) -- 外鍵約束,引用主表中的主鍵 
    );
    create table class  -- 班級表
    (
    c_id int primary key,
        c_name varchar(20) not null,
      c_info varchar(200)
    );

    查看錶的所有信息(約束):

    show create table 表名;
    -- 爲約束指定名稱
    create table student 
    (
    id int,
        name varchar(10) not null,  -- 非空約束
        age int, 
        sex varchar(8) ,
        IDCard varchar(18), 
        class_id int,
        constraint pk_id primary key (id),
        constraint ck_age check(age between 1 and 120),
        constraint ck_sex check(sex in ('male','female')),
        constraint uq_IDCard unique (IDCard),
        constraint fk_class_id foreign key (class_id) references class(c_id)
    );
  • 方式2:在創建表之後再添加約束

    create table student 
    (
    id int,
        name varchar(10) not null,  -- 非空約束只能在創建表時在列名後面指定
        age int, 
        sex varchar(8) ,
        IDCard varchar(18), 
        class_id int
    );

    ​ 爲表添加約束,語法:

    alter table 表名 add constraint 約束名 約束類型 約束內容

    ​ 示例:

    alter table student add constraint pk_id primary key (id);
    alter table student add constraint ck_age check(age between 1 and 120);
    alter table student add constraint ck_sex check(sex in ('male','female'));
    alter table student add constraint uq_IDCard unique (IDCard);
    alter table student add constraint fk_class_id foreign key (class_id) references class(c_id);

4. 刪除約束

​ 語法:

  • 刪除主鍵約束 alter table 表名 drop primary key
  • 刪除外鍵約束alter table 表名 drop foreign key 約束名稱
  • 刪除唯一約束alter table 表名 drop index 約束名稱
  • 刪除非空約束alter table 表名 modify 列名 數據類型 null

5. 注意事項

  • 創建表時,必須先創建主表,再創建從表
  • 刪除表時,必須先刪除從表,再刪除主表
  • 可以在創建表時指定級聯刪除,當主表數據被刪除時,將自動刪除從表中的相關數據
create table student  -- 學生表
(
    id int primary key,  -- 主鍵約束
    name varchar(10) not null,  -- 非空約束
    age int check(age between 1 and 120), -- 檢查約束
    sex varchar(8) not null check(sex in ('male','female')), -- 多種約束
    IDCard varchar(18) unique, -- 唯一約束
    class_id int, -- 外鍵列
    foreign key (class_id) references class(c_id) on delete cascade  -- 級聯刪除
);

十三、用戶和權限管理

1. 創建用戶並授予權限

​ 語法:

grant 權限列表 on 庫名.表名 to 用戶名@來源地址 identified by '密碼';

​ 示例:

grant select on test.emp to tom@localhost identified by '123';
grant select on shop.user to jack@localhost identified by '123';
grant select,update on shop.* to mike@'%' identified by '111'; 
grant delete on shop.user to mike@'%';
grant all on *.* to alice@'%' identified by '123';

​ 注:test庫是安裝時默認創建的,默認情況下所有用戶對該庫都擁有最大的權限

​ 只能管理員才具有創建用戶的權限

2. 查看權限

​ 語法:

show grants;  -- 查看自己的權限
show grants for 用戶名@來源地址;  -- 查看其他人的權限

3. 撤銷權限

​ 語法:

revoke 權限列表 on 庫名.表名 from 用戶名@來源地址

​ 示例:

revoke delete on shop.user from mike@'%';

4. 刪除用戶

​ 語法:

use mysql;
delete from user where user='用戶名';
flush privileges; -- 刷新權限

十四、事務處理

1. 簡介

​ transaction

​ 事務處理是用來保證數據操作的完整性

​ 一個業務由若干個一次性的操作組成,這些操作要麼都成功,要麼都失敗,如銀行轉賬

​ 事務特性ACID:

  • 原子性(Atomicity):不可再分
  • 一致性(Consistency):要保證數據前後的一致性
  • 隔離性(Isolation):兩個事務的操作互不干擾
  • 持久性(Durability):一旦事務提交,不可回滾

2. 事務操作

​ MySQL默認是自動提交事務的,將每一條語句都當作一個獨立的事務執行,可以通過autocommit關閉自動提交事務

​ 查看autocommit模式:show variables like 'autocommit'

​ 關閉自動提交:set autocommit=offset autocommit=0

​ 手動提交事務:commit

​ 手動回滾事務:rollback

MySQL零基礎入門視頻課程——筆記

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章