1. 程式人生 > >MySQL資料庫常見操作總結

MySQL資料庫常見操作總結

MySQL

E-R模型

  • 當前物理的資料庫都是按照E-R模型進行設計的
  • E表示entry,實體
  • R表示relationship,關係
  • 一個實體轉換為資料庫中的一個表
  • 關係描述兩個實體之間的對應規則,包括
    • 一對一
    • 一對多
    • 多對多
  • 關係轉換為資料庫表中的一個列 *在關係型資料庫中一行就是一個物件

三正規化

  • 經過研究和對使用中問題的總結,對於設計資料庫提出了一些規範,這些規範被稱為正規化
  • 第一正規化(1NF):列不可拆分
  • 第二正規化(2NF):唯一標識
  • 第三正規化(3NF):引用主鍵
  • 說明:後一個正規化,都是在前一個正規化的基礎上建立的

安裝

  • 安裝

    sudo apt-get install mysql-server mysql-client 然後按照提示輸入

管理服務

  • 啟動

    service mysql start

  • 停止

    service mysql stop

  • 重啟

    service mysql restart

允許遠端連線

  • 找到mysql配置檔案並修改

    sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf 將bind-address=127.0.0.1註釋

  • 登入mysql,執行命令

    grant all privileges on . to ‘root’@’%’ identified by ‘mysql’ with grant option; flush privileges;

  • 重啟mysql

資料完整性

  • 一個數據庫就是一個完整的業務單元,可以包含多張表,資料被儲存在表中
  • 在表中為了更加準確的儲存資料,保證資料的正確有效,可以在建立表的時候,為表新增一些強制性的驗證,包括資料欄位的型別、約束

欄位型別

  • 在mysql中包含的資料型別很多,這裡主要列出來常用的幾種
  • 數字:int,decimal
  • 字串:varchar,text
  • 日期:datetime
  • 布林:bit

約束

  • 主鍵primary key
  • 非空not null
  • 惟一unique
  • 預設default
  • 外來鍵foreign key

遠端連線

  • 一般在公司開發中,可能會將資料庫統一搭建在一臺伺服器上,所有開發人員共用一個數據庫,而不是在自己的電腦中配置一個數據庫

  • 執行命令

    mysql -h ip地址 -uroot -p

  • -h後面寫要連線的主機ip地址

  • -u後面寫連線的使用者名稱

  • -p回車後寫密碼

資料庫操作

  • 建立資料庫

    create database 資料庫名 charset=utf8;

  • 刪除資料庫

    drop database 資料庫名;

  • 切換資料庫

    use 資料庫名;

  • 檢視當前選擇的資料庫

    select database();

表操作

  • 檢視當前資料庫中所有表

    show tables;

  • 建立表

  • auto_increment表示自動增長 create table 表名(列及型別); 如: create table students( id int auto_increment primary key, sname varchar(10) not null );

  • 修改表

    alter table 表名 add|change|drop 列名 型別; 如: alter table students add birthday datetime;

  • 刪除表

    drop table 表名;

  • 查看錶結構

    desc 表名;

  • 更改表名稱

    rename table 原表名 to 新表名;

  • 查看錶的建立語句

    show create table ‘表名’;

資料操作

  • 查詢

    select * from 表名

  • 增加

    全列插入:insert into 表名 values(…) 預設插入:insert into 表名(列1,…) values(值1,…) 同時插入多條資料:insert into 表名 values(…),(…)…; 或insert into 表名(列1,…) values(值1,…),(值1,…)…;

  • 主鍵列是自動增長,但是在全列插入時需要佔位,通常使用0,插入成功後以實際資料為準

  • 修改

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

  • 刪除

    delete from 表名 where 條件

  • 邏輯刪除,本質就是修改操作update

    alter table students add isdelete bit default 0; 如果需要刪除則 update students isdelete=1 where …;

備份與恢復

資料備份

  • 進入超級管理員

    sudo -s

  • 進入mysql庫目錄

    cd /var/lib/mysql

  • 執行mysqldump命令

    mysqldump –uroot –p 資料庫名 > ~/Desktop/備份檔案.sql; 按提示輸入mysql的密碼

資料恢復

  • 連線mysqk,建立資料庫

  • 退出連線,執行如下命令

    mysql -uroot –p 資料庫名 < ~/Desktop/備份檔案.sql 根據提示輸入mysql密碼

簡介

  • 查詢的基本語法

    select * from 表名;

  • from關鍵字後面寫表名,表示資料來源於是這張表

  • select後面寫表中的列名,如果是*表示在結果中顯示錶中所有列

  • 在select後面的列名部分,可以使用as為列起別名,這個別名出現在結果集中

  • 如果要查詢多個列,之間使用逗號分隔

消除重複行

  • 在select後面列前使用distinct可以消除重複的行

    select distinct gender from students;

條件

  • 使用where子句對錶中的資料篩選,結果為true的行會出現在結果集中

  • 語法如下:

    select * from 表名 where 條件;

比較運算子

  • 等於=

  • 大於>

  • 大於等於>=

  • 小於<

  • 小於等於<=

  • 不等於!=或<>

  • 查詢編號大於3的學生

    select * from students where id>3;

  • 查詢編號不大於4的科目

    select * from subjects where id<=4;

  • 查詢姓名不是“黃蓉”的學生

    select * from students where sname!=‘黃蓉’;

  • 查詢沒被刪除的學生

    select * from students where isdelete=0;

邏輯運算子

  • and

  • or

  • not

  • 查詢編號大於3的女同學

    select * from students where id>3 and gender=0;

  • 查詢編號小於4或沒被刪除的學生

    select * from students where id<4 or isdelete=0;

模糊查詢

  • like

  • %表示任意多個任意字元

  • _表示一個任意字元

  • 查詢姓黃的學生

    select * from students where sname like ‘黃%’;

  • 查詢姓黃並且名字是一個字的學生

    select * from students where sname like ‘黃_’;

  • 查詢姓黃或叫靖的學生

    select * from students where sname like ‘黃%’ or sname like ‘%靖%’;

範圍查詢

  • in表示在一個非連續的範圍內

  • 查詢編號是1或3或8的學生

    select * from students where id in(1,3,8);

  • between … and …表示在一個連續的範圍內

  • 查詢學生是3至8的學生

    select * from students where id between 3 and 8;

  • 查詢學生是3至8的男生

    select * from students where id between 3 and 8 and gender=1;

空判斷

  • 注意:null與’'是不同的

  • 判空is null

  • 查詢沒有填寫地址的學生

    select * from students where hometown is null;

  • 判非空is not null

  • 查詢填寫了地址的學生

    select * from students where hometown is not null;

  • 查詢填寫了地址的女生

    select * from students where hometown is not null and gender=0;

優先順序

  • 小括號,not,比較運算子,邏輯運算子
  • and比or先運算,如果同時出現並希望先算or,需要結合()使用

聚合

  • 為了快速得到統計資料,提供了5個聚合函式

  • count(*)表示計算總行數,括號中寫星與列名,結果是相同的

  • 查詢學生總數

    select count(*) from students;

  • max(列)表示求此列的最大值

  • 查詢女生的編號最大值

    select max(id) from students where gender=0;

  • min(列)表示求此列的最小值

  • 查詢未刪除的學生最小編號

    select min(id) from students where isdelete=0;

  • sum(列)表示求此列的和

  • 查詢男生的編號之後

    select sum(id) from students where gender=1;

  • avg(列)表示求此列的平均值

  • 查詢未刪除女生的編號平均值

    select avg(id) from students where isdelete=0 and gender=0;

分組

  • 按照欄位分組,表示此欄位相同的資料會被放到一個組中

  • 分組後,只能查詢出相同的資料列,對於有差異的資料列無法出現在結果集中

  • 可以對分組後的資料進行統計,做聚合運算

  • 語法:

    select 列1,列2,聚合… from 表名 group by 列1,列2,列3…

  • 查詢男女生總數

    select gender as 性別,count(*) from students group by gender;

  • 查詢各城市人數

    select hometown as 家鄉,count(*) from students group by hometown;

分組後的資料篩選

  • 語法:

    select 列1,列2,聚合… from 表名 group by 列1,列2,列3… having 列1,…聚合…

  • having後面的條件運算子與where的相同

  • 查詢男生總人數

    方案一 select count(*) from students where gender=1;

    方案二: select gender as 性別,count(*) from students group by gender having gender=1;

對比where與having

  • where是對from後面指定的表進行資料篩選,屬於對原始資料的篩選
  • having是對group by的結果進行篩選

排序

  • 為了方便檢視資料,可以對資料進行排序

  • 語法:

    select * from 表名 order by 列1 asc|desc,列2 asc|desc,…

  • 將行資料按照列1進行排序,如果某些行列1的值相同時,則按照列2排序,以此類推

  • 預設按照列值從小到大排列

  • asc從小到大排列,即升序

  • desc從大到小排序,即降序

  • 查詢未刪除男生學生資訊,按學號降序

    select * from students where gender=1 and isdelete=0 order by id desc;

  • 查詢未刪除科目資訊,按名稱升序

    select * from subject where isdelete=0 order by stitle;

獲取部分行

  • 當資料量過大時,在一頁中檢視資料是一件非常麻煩的事情

  • 語法

    select * from 表名 limit start,count

  • 從start開始,獲取count條資料

  • start索引從0開始

示例:分頁

  • 已知:每頁顯示m條資料,當前顯示第n頁

  • 求總頁數:此段邏輯後面會在python中實現

    • 查詢總條數p1
    • 使用p1除以m得到p2
    • 如果整除則p2為總數頁
    • 如果不整除則p2+1為總頁數
  • 求第n頁的資料

    select * from students where isdelete=0 limit (n-1)*m,m

外來鍵

  • 思考:怎麼保證關係列資料的有效性呢?任何整數都可以嗎?

  • 答:必須是學生表中id列存在的資料,可以通過外來鍵約束進行資料的有效性驗證

  • 為stuid新增外來鍵約束

    alter table scores add constraint stu_sco foreign key(stuid) references students(id);

  • 此時插入或者修改資料時,如果stuid的值在students表中不存在則會報錯

  • 在建立表時可以直接建立約束

    create table scores( id int primary key auto_increment, stuid int, subid int, score decimal(5,2), foreign key(stuid) references students(id), foreign key(subid) references subjects(id) );

外來鍵的級聯操作

  • 在刪除students表的資料時,如果這個id值在scores中已經存在,則會拋異常

  • 推薦使用邏輯刪除,還可以解決這個問題

  • 可以建立表時指定級聯操作,也可以在建立表後再修改外來鍵的級聯操作

  • 語法

    alter table scores add constraint stu_sco foreign key(stuid) references students(id) on delete cascade;

  • 級聯操作的型別包括:

    • restrict(限制):預設值,拋異常
    • cascade(級聯):如果主表的記錄刪掉,則從表中相關聯的記錄都將被刪除
    • set null:將外來鍵設定為空
    • no action:什麼都不做
  • 結論:當需要對有關係的多張表進行查詢時,需要使用連線join

連線查詢

  • 連線查詢分類如下:
    • 表A inner join 表B:表A與表B匹配的行會出現在結果中
    • 表A left join 表B:表A與表B匹配的行會出現在結果中,外加表A中獨有的資料,未對應的資料使用null填充
    • 表A right join 表B:表A與表B匹配的行會出現在結果中,外加表B中獨有的資料,未對應的資料使用null填充
  • 在查詢或條件中推薦使用“表名.列名”的語法
  • 如果多個表中列名不重複可以省略“表名.”部分
  • 如果表的名稱太長,可以在表名後面使用’ as 簡寫名’或’ 簡寫名’,為表起個臨時的簡寫名稱

自關聯

  • citys表的proid表示城市所屬的省,對應著provinces表的id值

字串函式

  • 檢視字元的ascii碼值ascii(str),str是空串時返回0

    select ascii(‘a’);

  • 檢視ascii碼值對應的字元char(數字)

    select char(97);

  • 拼接字串concat(str1,str2…)

    select concat(12,34,‘ab’);

  • 包含字元個數length(str)

    select length(‘abc’);

  • 擷取字串

    • left(str,len)返回字串str的左端len個字元

    • right(str,len)返回字串str的右端len個字元

    • substring(str,pos,len)返回字串str的位置pos起len個字元

      select substring(‘abc123’,2,3);

  • 去除空格

    • ltrim(str)返回刪除了左空格的字串str

    • rtrim(str)返回刪除了右空格的字串str

    • trim([方向 remstr from str)返回從某側刪除remstr後的字串str,方向詞包括both、leading、trailing,表示兩側、左、右

      select trim(’ bar '); select trim(leading ‘x’ FROM ‘xxxbarxxx’); select trim(both ‘x’ FROM ‘xxxbarxxx’); select trim(trailing ‘x’ FROM ‘xxxbarxxx’);

  • 返回由n個空格字元組成的一個字串space(n)

    select space(10);

  • 替換字串replace(str,from_str,to_str)

    select replace(‘abc123’,‘123’,‘def’);

  • 大小寫轉換,函式如下

    • lower(str)

    • upper(str)

      select lower(‘aBcD’);

數學函式

  • 求絕對值abs(n)

    select abs(-32);

  • 求m除以n的餘數mod(m,n),同運算子%

    select mod(10,3); select 10%3;

  • 地板floor(n),表示不大於n的最大整數

    select floor(2.3);

  • 天花板ceiling(n),表示不小於n的最大整數

    select ceiling(2.3);

  • 求四捨五入值round(n,d),n表示原數,d表示小數位置,預設為0

    select round(1.6);

  • 求x的y次冪pow(x,y)

    select pow(2,3);

  • 獲取圓周率PI()

    select PI();

  • 隨機數rand(),值為0-1.0的浮點數

    select rand();

  • 還有其它很多三角函式,使用時可以查詢文件

日期時間函式

  • 獲取子值,語法如下

    • year(date)返回date的年份(範圍在1000到9999)

    • month(date)返回date中的月份數值

    • day(date)返回date中的日期數值

    • hour(time)返回time的小時數(範圍是0到23)

    • minute(time)返回time的分鐘數(範圍是0到59)

    • second(time)返回time的秒數(範圍是0到59)

      select year(‘2016-12-21’);

  • 日期計算,使用±運算子,數字後面的關鍵字為year、month、day、hour、minute、second

    select ‘2016-12-21’+interval 1 day;

  • 日期格式化date_format(date,format),format引數可用的值如下

    • 獲取年%Y,返回4位的整數

      • 獲取年%y,返回2位的整數
      • 獲取月%m,值為1-12的整數
    • 獲取日%d,返回整數

      • 獲取時%H,值為0-23的整數
      • 獲取時%h,值為1-12的整數
      • 獲取分%i,值為0-59的整數
      • 獲取秒%s,值為0-59的整數

      select date_format(‘2016-12-21’,’%Y %m %d’);

  • 當前日期current_date()

    select current_date();

  • 當前時間current_time()

    select current_time();

  • 當前日期時間now()

    select now();

檢視

  • 對於複雜的查詢,在多次使用後,維護是一件非常麻煩的事情

  • 解決:定義檢視

  • 檢視本質就是對查詢的一個封裝

  • 定義檢視

    create view stuscore as select students.*,scores.score from scores inner join students on scores.stuid=students.id;

  • 檢視的用途就是查詢

    select * from stuscore;

事務

  • 當一個業務邏輯需要多個sql完成時,如果其中某條sql語句出錯,則希望整個操作都退回
  • 使用事務可以完成退回的功能,保證業務邏輯的正確性
  • 事務四大特性(簡稱ACID)
    • 原子性(Atomicity):事務中的全部操作在資料庫中是不可分割的,要麼全部完成,要麼均不執行
    • 一致性(Consistency):幾個並行執行的事務,其執行結果必須與按某一順序序列執行的結果相一致
    • 隔離性(Isolation):事務的執行不受其他事務的干擾,事務執行的中間結果對其他事務必須是透明的
    • 永續性(Durability):對於任意已提交事務,系統必須保證該事務對資料庫的改變不被丟失,即使資料庫出現故障
  • 要求:表的型別必須是innodb或bdb型別,才可以對此表使用事務