MYSQL 語句高級應用之 多表查詢及事務(二)

、SQL語句類型

1、DDL:數據定義語言

通常用於定義數據庫對像

常見的數據庫對象

數據庫,表,索引,視圖,存儲過程,存儲函數,約束,觸發器,事件調度器。

2、DML:數據操作語言

GRUD: insert,select,update,delete

3、DCL:數據控制語言

GRANT,REVOKE

4、事務:

start transaction 啓動事務,commit 提交事務,rollback 滾回,save point 保存點。

二、DDL語句的應用

1、數據庫的操作語句

1)創建:create database|schema [if not exists] dbname;

msyql> create datebase mytestdb;

character set= 定義字符集

collate 定義默認排序規則

2)刪除:drop database|schema [if exists] dbname;

mysql> drop database hellodb;

3)修改:alter database|schema dbname

升級數據字典 -upgrade data dircttory name

2、表的相關操作語句

查看錶的狀態

mysql> show table status\G


1)存儲引擎類型,又稱作表的類型

MyISAM表不支持事務

tbname.MYD 存儲數據,tbname.MYI 存儲索引,tbname.frm 表的定義

InnoDB表支持事務

tbname.frm 表的定義

tbname.ibd 表空間用於存儲數據和索

開啓表空間的方法:setbal innodb_file_per_table=1

mysql> show session variables like 'innodb%';
mysql> set global innodb_file_per_table = 1;


2)表的選項

engine=engine_name 定義存儲引擎

delay_key_write={0|1} 是否延遲鍵寫入

tablespace tablespace_name 明確指定使用的表空間

auto_increment 自動增長值

data dirctory /path/to 明確數據字典保存路徑

max rows=value 最多能存儲的行數

3)創建表

方式一:create table tb_name (col1 defination,col2 defination,...);自定義表的參數屬性

CREATE TABLE `students` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `name` char(30) NOT NULL,
  `age` tinyint(3) unsigned DEFAULT NULL,
  `gender` char(1) DEFAULT 'm',
  `course` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8


方式二:create table tb_name [(defination)] select clause; 依據查詢結果創建表

mysql> create table teststudents select name,age,gender from students;


方式三:create table tb_name like old_table_name; 依據老表創建表

mysql> create table newstudents like students;


4)刪除表

drop table [if exists] tb_name;

mysql> drop table newstudents;


5)改表名

rename table tb_name to new_name;

mysql> rename table teststudents to students1;


6)修改表

查看如何修改表

mysql> help alter table


alter table tb_name add colfinaton [{frist|after col_name}];增加新字段

mysql> alter table students1 add `course` varchar(50) NOT NULL after gender;


alter table tb_name drop colname;刪除某個字段

mysql> alter table students drop course;

alter table tb_name modify col defination [{frist|after col_name}];

修改某個字段的屬性

alter table tb_name change old_col_name new_col_name column_defination [{frist|after col_name}];

修改某字段的名稱,並指定其位置

mysql> alter table students change course `courses` varchar(50) NOT NULL;

alter teable tb_name rename to new_name;改表名

mysql> alter table students1 rename to newstudents;


三、DML語句的應用

增刪查改:insert,delete,select,update

1、增,insert語句的使用

1)insert into tb_name [(col1,col2,...)] {value|values}();

mysql> insert into students (name,age,gender,courses) values ('zhang wuji',20,'M','Q
Query OK, 1 row affected (0.06 sec)

插入數值數據,不需要引號;

字符數據,需要引號;

空值,null。

2)insert into tb_name set col_name=value,...;

mysql> insert into students set name='Yang xiao',age=45,gender='M',courses='Jiuyang Shengong';
Query OK, 1 row affected (0.10 sec)
mysql> select * from students;
+----+--------------+------+--------+-----------------------+
| id | name         | age  | gender | courses               |
+----+--------------+------+--------+-----------------------+
|  1 | Ling Huchong |   24 | M      | Hamogong              |
|  2 | Huang Rong   |   19 | F      | Chilian Shenzhang     |
|  3 | Lu Wushuang  |   18 | F      | Jiuying Shengong      |
|  4 | Zhu Ziliu    |   52 | M      | Pixie Jianfa          |
|  5 | Chen Jialuo  |   22 | M      | Xianglong Shiba Zhang |
|  6 | zhang wuji   |   20 | M      | Qiankun Daluoqi       |
|  7 | Yang xiao    |   45 | M      | Jiuyang Shengong      |
+----+--------------+------+--------+-----------------------+

3)insert into tb_name (col1,..) select clause;

mysql> insert into newstudents (name,age,gender,course) value ('Zhang Sanfeng',80,'M','Tai Ji');
Query OK, 1 row affected (0.05 sec)
mysql> insert into students (name,age,gender,courses) select * from newstudents where name='Zhang Sanfeng';
Query OK, 1 row affected (0.08 sec)
Records: 1  Duplicates: 0  Warnings: 0

4)replace into tb_name (col1,..)

替換操作,有則替換,無則插入

2、刪,delete語句的使用

delete from tb_name where vlaue;

mysql> delete from newstudents where name='Zhu Ziliu';
Query OK, 1 row affected (0.09 sec)

3、改,update語句的使用

update from tb_name col1,... where vlaue;

mysql> update newstudents set age=28 where name='Chen Jialuo';
Query OK, 1 row affected (0.05 sec)
Rows matched: 1  Changed: 1  Warnings: 0

4、清空並重置表,效果比刪要好

truncate table tb_name;

查看最後一次插入的數據的ID號

mysql>  select last_insert_ID();
+------------------+
| last_insert_ID() |
+------------------+
|                9 |
+------------------+
1 row in set (0.00 sec)

四、DML語句之查語句的使用

1、表的查詢方式

全表查詢和使用索引查詢,表只要有一個索引,完成查詢至少有兩條路徑。

2、查看所有字段信息

select * from tb_name;

mysql> select * from newstudents;
+---------------+------+--------+---------+
| name          | age  | gender | courses |
+---------------+------+--------+---------+
| Ling Huchong  |   24 | M      |         |
| Huang Rong    |   19 | F      |         |
| Lu Wushuang   |   18 | F      |         |
| Chen Jialuo   |   28 | M      |         |
| Zhang Sanfeng |   80 | M      | Tai Ji  |
+---------------+------+--------+---------+
5 rows in set (0.00 sec)

3、基於行與字段的查詢

1)投影:select col1.col2 from tb_name;限定字段

mysql> select age=18 from newstudents;
+--------+
| age=18 |
+--------+
|      0 |
|      0 |
|      1 |
|      0 |
|      0 |
+--------+
5 rows in set (0.00 sec)

2)選擇:select * from where clause;限定行

mysql> select * from newstudents where name='Huang Rong';
+------------+------+--------+---------+
| name       | age  | gender | courses |
+------------+------+--------+---------+
| Huang Rong |   19 | F      |         |
+------------+------+--------+---------+
1 row in set (0.01 sec)

3)合併:select col1,col2 from tb_name where clause;即限定字段又限定行

mysql> select age from newstudents where name='Lu Wushuang';
+------+
| age  |
+------+
|   18 |
+------+
1 row in set (0.00 sec)


4、where子句

比較表達式+算術表達式

1)連續集合:between value1 and value2;

mysql> select * from students where age between 20 and 24;
+----+--------------+------+--------+-----------------------+
| id | name         | age  | gender | courses               |
+----+--------------+------+--------+-----------------------+
|  1 | Ling Huchong |   24 | M      | Hamogong              |
|  5 | Chen Jialuo  |   22 | M      | Xianglong Shiba Zhang |
|  6 | zhang wuji   |   20 | M      | Qiankun Daluoqi       |
+----+--------------+------+--------+-----------------------+
3 rows in set (0.00 sec)


2)離散集合:in (element1,element2,...);

mysql> select * from students where id in (2,3,4);
+----+-------------+------+--------+-------------------+
| id | name        | age  | gender | courses           |
+----+-------------+------+--------+-------------------+
|  2 | Huang Rong  |   19 | F      | Chilian Shenzhang |
|  3 | Lu Wushuang |   18 | F      | Jiuying Shengong  |
|  4 | Zhu Ziliu   |   52 | M      | Pixie Jianfa      |
+----+-------------+------+--------+-------------------+
3 rows in set (0.00 sec)


3)空集合與非空集合:is null;

is not null;

4)支持通配:like {%|_};

5)支持正則表達式:{relike|regexp} .,*,^,/>....

6)組合條件函數:and/&& 與,or/|| 或,not/!非,xor 異或

7) 算術表達式:>,<,>=,<=

mysql> select * from students where id<4 and gender='F';
+----+-------------+------+--------+-------------------+
| id | name        | age  | gender | courses           |
+----+-------------+------+--------+-------------------+
|  2 | Huang Rong  |   19 | F      | Chilian Shenzhang |
|  3 | Lu Wushuang |   18 | F      | Jiuying Shengong  |
+----+-------------+------+--------+-------------------+
2 rows in set (0.00 sec)


8)聚合函數:max() 求最大值,min() 求最小值,avg() 求平均值,count() 計數器,sum() 求和。

求最大值

五、查詢語句中的表相關查詢

1、表相關的查詢類型:

單表查詢,聯結查詢(join),聯合查詢(union)

1)聯結查詢:多表查詢,表與表之間通過某種關係(即相同的字段)組合起來完整地查詢。

2)聯合查詢:將兩個和兩個以上的select語句查詢結果聯合起來。

2、表聯結查詢

1)交叉聯結:兩個表做笛卡爾乘積,產生結果在本地臨時緩存下來。

2)內聯結:又稱爲自然聯結,讓兩張表對應的字段的值建立等值連接關係。

3)外聯結:又分爲左外聯結和右外聯結及全外聯結

左外聯結:兩個或多個表以左邊表爲標準查詢。

left_table left join right_table on condition;

右外聯結:兩個或多個表以右邊表爲標準查詢。

right_table right join left_table on condition

4)自聯結:自己與自己聯結,同一張表定義兩個別名

sometables as alias1 inter join sometable as alias2 on alias1 filed = alias2 filed

3、表的聯合查詢

select clause union select clause

4、表的子查詢

1)用於where的子查詢

select clause from tb_name where col...

用於比較表達式中的子查詢;

用於exists中的子查詢;

用於in中的子查詢。

2)用於from中的子查詢

select col,... from tb_name

注:mysql對於查詢的優化很有限,儘量不要使用子查詢。


多表查詢實戰案例

導入hellodb.sql,完成以下題目:

啓用hellodb表

mysql> use hellodb;
Database changed
mysql> show tables;
+-------------------+
| Tables_in_hellodb |
+-------------------+
| classes           |
| coc               |
| courses           |
| mytest            |
| scores            |
| students          |
| teachers          |
| toc               |
+-------------------+
8 rows in set (0.00 sec)


1、顯示前5位同學的姓名、課程及成績;

mysql> select Name,Course,Score from students,courses,scores where students.StuID=scores.StuID and scores.CourseID=courses.CourseID group by students.StuID  limit 5;
+-------------+----------------+-------+
| Name        | Course         | Score |
+-------------+----------------+-------+
| Shi Zhongyu | Kuihua Baodian |    77 |
| Shi Potian  | Kuihua Baodian |    47 |
| Xie Yanke   | Kuihua Baodian |    88 |
| Ding Dian   | Daiyu Zanghua  |    71 |
| Yu Yutong   | Hamo Gong      |    39 |
+-------------+----------------+-------+
5 rows in set (0.06 sec)

2、顯示其成績高於80的同學的名稱及課程;

mysql> select Name,Course,Score from students,courses,scores where students.StuID=scores.StuID and scores.CourseID=courses.CourseID and Score>=80 group by Name;
+-------------+----------------+-------+
| Name        | Course         | Score |
+-------------+----------------+-------+
| Ding Dian   | Kuihua Baodian |    89 |
| Lin Daiyu   | Jinshe Jianfa  |    93 |
| Shi Potian  | Daiyu Zanghua  |    97 |
| Shi Qing    | Hamo Gong      |    96 |
| Shi Zhongyu | Weituo Zhang   |    93 |
| Xi Ren      | Hamo Gong      |    86 |
| Xie Yanke   | Kuihua Baodian |    88 |
+-------------+----------------+-------+
7 rows in set (0.00 sec)

3、求前8位同學每位同學自己兩門課的平均成績,並按降序排列;

mysql> select students.StuID,Name,avg(Score) from students,courses,scores where students.StuID=scores.StuID and scores.CourseID=courses.CourseID group by Name order by avg(Score) desc;
+-------+-------------+------------+
| StuID | Name        | AVG(Score) |
+-------+-------------+------------+
|     6 | Shi Qing    |    96.0000 |
|     1 | Shi Zhongyu |    85.0000 |
|     7 | Xi Ren      |    84.5000 |
|     3 | Xie Yanke   |    81.5000 |
|     4 | Ding Dian   |    80.0000 |
|     8 | Lin Daiyu   |    75.0000 |
|     2 | Shi Potian  |    72.0000 |
|     5 | Yu Yutong   |    51.0000 |
+-------+-------------+------------+
8 rows in set (0.00 sec)


4、顯示每門課程課程名稱及學習的同學的個數;

mysql> select course,count(stuID) from students,courses,coc where students.ClassID=coc.ClassID and coc.CourseID=courses.CourseID group by course;
+----------------+--------------+
| course         | count(stuID) |
+----------------+--------------+
| Dagou Bangfa   |            4 |
| Daiyu Zanghua  |            8 |
| Hamo Gong      |            5 |
| Jinshe Jianfa  |            7 |
| Kuihua Baodian |           11 |
| Taiji Quan     |            7 |
| Weituo Zhang   |            3 |
+----------------+--------------+
7 rows in set (0.05 sec)


六、mysql事務處理時鎖機制

1、鎖的概念:鎖是保證併發性在臨界區實現資源保護的一種機制。

2、鎖的類型:表級鎖,行級鎖,頁級鎖。

MyISAM引擎只支持表級鎖,而InnoDB引擎還支持行級鎖。

3、加鎖方式:

施加讀鎖,也稱之爲共享鎖,則其他用戶能讀不能寫;

施加寫鎖,也稱之爲獨佔鎖,則其他用戶既不能讀更不能寫;

4、加鎖與解鎖的方案:

施加顯式鎖 lock tables tb_name,... {read|write};

施加隱式鎖 select [ for update | lock in share mode ];

釋放鎖 unlock tables;

七、事務

1、事務系統中的“ACID”

1)A/ 原子性:同一組的DML語句,要麼都執行,要麼都不執行;

2)C/ 一致性:數據從一種狀態轉換到另外一種狀態總量不變;

3) I/ 隔離性:多個事務同時操作數據時可以互不干擾;

4)D/ 持久性:數據一旦提交不能丟失,未提交可以撤銷,事務提交,則立即寫入磁盤。

2、開啓事務處理

start transaction

3、保存事務節點

savepoint point_name

4、滾回指定事務節點

rollback [ to somepoint ]

5、提交事務

commit

6、事務的隔離性,事務都是具有嚴格的隔離級別的,將兩個或多個事務隔離開來進行處理。

1)讀未提交:read uncommitted

讀過後沒有提交,能在不同的終端修改數據時,立即從別的終端讀取,導致事務之間存在干擾。

2)讀提交:read commited

讀過後等待提交,不能再讀取別的終端滾回去的數據,只能等待對方提交後才能讀取。

3)可重讀:repeatble read ,mysql服務默認的隔離級別

它確保同一事務的多個實例在併發讀取數據時,會看到同樣的數據行。但是會帶來幻讀效果。

4)可串行化:seriablizable

可串行化的事務只能一個接着一個的執行,不能併發執行,安全性最高,並解決了幻讀。



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