1. SQL概述
- 結(jié)構(gòu)化查詢語言(Structured Query Language,SQL)是專門用來與數(shù)據(jù)庫通信的語言净刮,它可以幫助用戶操作關(guān)系數(shù)據(jù)庫。
- SQL的特點:
- SQL不是某個特定數(shù)據(jù)庫供應(yīng)商專有的語言
- SQL簡單易學(xué)
- SQL強大茧球、靈活庭瑰,可以進行非常復(fù)雜和高級的數(shù)據(jù)庫操作
- SQL的組成
- 數(shù)據(jù)查詢
- 數(shù)據(jù)定義語言(Data Definition Language, DDL)
- CREATE:創(chuàng)建數(shù)據(jù)庫或數(shù)據(jù)庫對象
- ALTER:對數(shù)據(jù)庫或數(shù)據(jù)庫對象進行修改
- DROP:刪除數(shù)據(jù)庫或數(shù)據(jù)庫對象
- 數(shù)據(jù)操縱語言(Data Manipulation Language, DML)
- SELECT:從表或視圖中檢索數(shù)據(jù)
- INSERT:將數(shù)據(jù)插入到表或視圖中
- UPDATE:修改表或視圖中的數(shù)據(jù)
- DELETE:從表或視圖中刪除數(shù)據(jù)
- 數(shù)據(jù)控制語言(Data Control Language, DCL)
- GRANT:用于授予權(quán)限
- REVOKE:用于收回權(quán)限
- 嵌入式和動態(tài)SQL規(guī)則:嵌入式和動態(tài)SQL規(guī)則規(guī)定了SQL語句在高級語言程序設(shè)計中使用的規(guī)范方法,以便適應(yīng)較為復(fù)雜的應(yīng)用抢埋。
- SQL調(diào)用和會話規(guī)則:以便提高SQL的靈活性弹灭、有效性督暂、共享性以及SQL具有更多的高級語言特征。
- SQL例程
- 調(diào)用規(guī)則
2. MySQL預(yù)備知識
- SQL使用基礎(chǔ)
- 關(guān)系數(shù)據(jù)庫管理系統(tǒng)(RDBMS):優(yōu)點是體積小穷吮、速度快逻翁、開放源代碼、遵循GPL
- 構(gòu)架方式
- LAMP:Linux捡鱼、Apache八回、MySQL、PHP/Perl/Python
- WAMP:Windows驾诈、Apache缠诅、MySQL、PHP/Perl/Python
- MySQL擴展語言要素
-
常量:也稱字面值或標量值
- 字符串常量
- 數(shù)值常量
- 十六進制常量
- 時間日期常量
- 位字段值
- 布爾值
- NULL值
-
變量
- 用戶變量:用戶變量前常添加一個符號@乍迄,用于將其與列名區(qū)分開
- 系統(tǒng)變量:大多數(shù)系統(tǒng)變量應(yīng)用于其他SQL語句中時管引,必須在系統(tǒng)變量前添加兩個@
-
運算符
分類 運算符 算術(shù)運算符 +、-闯两、*褥伴、/、% 位運算符 &漾狼、|重慢、^、~逊躁、<<似踱、>> 比較運算符 =、 >稽煤、 <屯援、 >=、 <=念脯、 <>(不等于)狞洋、 !=、 <=>(相等或都等于空) 邏輯運算符 NOT或!绿店、AND或&&吉懊、OR或||、XOR(邏輯異或) 表達式:是常量假勿、變量借嗽、列名、復(fù)雜計算转培、運算符和函數(shù)的組合
-
內(nèi)置函數(shù)
函數(shù) 數(shù)學(xué)函數(shù) ABS() 聚合函數(shù) COUNT() 字符串函數(shù) ASCⅡ() 日期和時間函數(shù) NOW() 加密函數(shù) ENCODE() 控制流程函數(shù) IF() 格式化函數(shù) FORMAT() 類型轉(zhuǎn)換函數(shù) CAST() 系統(tǒng)信息函數(shù) USER()
-
3. 數(shù)據(jù)定義
1.數(shù)據(jù)庫模式定義
-
創(chuàng)建數(shù)據(jù)庫:使用CREATE DATABASE或CREATE SCHEMAS
CREATE {DATABASE | SCHEMAS} [IF NOT EXISTS] db_name [DEFAULT] CHARACTER SET [=] charset_name [DEFAULT] COLLATE [=] collation_name //例 create database if not exists db_name;
-
設(shè)置默認值:使用DEFAULT
default character set charset_name; default collate collation_name;
-
查看數(shù)據(jù)庫:使用SHOW DATABASES或SHOW SCHEMA
show databases db_name; show databases like '_name'; // LIKE關(guān)鍵字用于匹配指定的數(shù)據(jù)庫名稱 show databases where expr; // WHERE從句用于指定數(shù)據(jù)庫名稱查詢范圍的條件
-
選擇數(shù)據(jù)庫:使用USE恶导,從一個數(shù)據(jù)庫“跳轉(zhuǎn)”到另一個數(shù)據(jù)庫
use db_name;
-
修改數(shù)據(jù)庫:ALTER DATABASE
alter database db_name default character set gb2312 default collate gb2312_chinese_ci;
-
刪除數(shù)據(jù)庫:DROP
drop database if exists db_name;
2.表定義
-
創(chuàng)建表:
- 數(shù)據(jù)表是關(guān)系數(shù)據(jù)庫中最重要、最基本的數(shù)據(jù)對象浸须,也是數(shù)據(jù)存儲的基本單位惨寿。
- 數(shù)據(jù)表被定義為字段的集合邦泄,按行和列的格式來存儲,每一行代表一條記錄裂垦,每一列代表記錄中一個字段的取值顺囊。
create table table_name ( 字段名 數(shù)據(jù)類型 [列級完整性約束條件] [默認值], 字段名N 數(shù)據(jù)類型 [列級完整性約束條件] [默認值], )[engint = 引擎類型];
數(shù)據(jù)類型 整型 int 浮點型 double 布爾型 bool 日期型 date 時間戳 timestamp 時間型 time 定長字符類型 char 可變長字符 varchar 示例:
mysql> use mysql_test Database changed // create temporary table:則為臨時表 mysql> create table customers -> ( -> c_id int not null auto_increment, // auto_increment:為當(dāng)前列設(shè)置自增屬性 -> c_name char(50) not null, -> c_sex char(1) not null default 0, // default:設(shè)置默認值 -> c_address char(50) null, // null:可為空 -> c_contact char(50) null, -> primary key(c_id) // primary key():指定主鍵 -> ); Query OK, 0 rows affected (0.06 sec)
-
更新表
使用ALTER TABLE語句,增加或刪減列蕉拢、創(chuàng)建或取消索引特碳、更改原有列的數(shù)據(jù)類型、重新命名列或表晕换、更改表的評注和表的引擎類型午乓、為表重新創(chuàng)建觸發(fā)器、存儲過程闸准、索引和外檢等硅瞧。
-
ADD [COLUMN]子句
向數(shù)據(jù)庫
mysql_test
的表customers
中添加一列,并命名為c_city
恕汇,要求不能為NULL
,默認字符串wuhan
或辖,且該列位于原表c_sex
之后瘾英。mysql> alter table mysql_test.customers -> add column c_city char(10) not null default 'wuhan' after c_sex;
-
CHANGE [COLUMN]子句:修改表中列的名稱或數(shù)據(jù)類型
mysql> alter table mysql_test.customers -> change column c_sex sex char(1) not null default "m";
-
ALTER [COLUMN]子句:修改或刪除表中列的默認值
mysql> alter table mysql_test.customers -> alter column c_city set default 'beijing';
-
MODIFY [COLUMN]子句:只修改指定列的數(shù)據(jù)類型,不會干涉它的列名颂暇。
mysql> alter table mysql_test.customers -> modify column c_name char(20) first;
-
DROP [COLUMN]子句:刪除表中多余的列
mysql> alter table mysql_test.customers -> drop column c_contact;
-
RENAME [TO]子句:為表重新賦予一個表名
mysql> alter table mysql_test.customers -> rename to mysql_test.backup_customers; // 或 mysql> rename table mysql_test.backup_customers to mysql_test.customers;
-
-
刪除表
drop table if exists mysql_test.table_name;
-
查看表
mysql> show columns from customers in mysql_test; // 或 mysql> describe mysql_test.customers; // 或 mysql> desc mysql_test.customers;
3.索引定義
- 索引是提高數(shù)據(jù)文件訪問效率的有效方法
- 索引存在的弊端:
- 索引是以文件的形式存儲的缺谴,如果有大量的索引,索引文件可能比數(shù)據(jù)文件更快達到最大的文件尺寸耳鸯。
- 索引在提高查詢速度的同時湿蛔,會降低更新表的速度。
- 分類:索引通常被創(chuàng)建成單列索引和組合索引
- 普通索引(INDEX 或 KEY)
- 唯一性索引(UNIQUE)
- 主鍵(PRIMARY KEY)
-
索引的創(chuàng)建:
使用CREATE INDEX語句創(chuàng)建
在數(shù)據(jù)庫
mysql_test
的表customers
上县爬,根據(jù)客戶姓名前三個字符創(chuàng)建一個升序普通索引index_customers
阳啥。mysql> create index index_customers -> on mysql_test.customers(c_name(3) ASC);
在數(shù)據(jù)庫
mysql_test
的表customers
上,根據(jù)客戶id和姓名創(chuàng)建一個組合索引index_cust
财喳。mysql> create index index_cust -> on mysql_test.customers(c_id, c_name);
使用CREATE TABLE語句創(chuàng)建:
創(chuàng)建表的同時創(chuàng)建該表的主鍵:
mysql> create table customers -> ( -> c_id int not null auto_increment, -> primary key(c_id) -> );
創(chuàng)建表的同時創(chuàng)建該表的索引:
mysql> create table customers -> ( -> c_name char(50) not null, ->index index_name(c_name) -> );
創(chuàng)建表的同時創(chuàng)建該表的唯一性索引:
mysql> create table customers -> ( -> c_sex char(1) not null default 0, -> unique index index_sex(c_sex) -> );
創(chuàng)建表的同時創(chuàng)建該表的外鍵:
mysql> create table customers -> ( -> c_address char(50) null, -> foreign key index_address(c_address) -> );
在已有數(shù)據(jù)庫
mysql_test
上新建一個包含產(chǎn)品賣家id號察迟,姓名、地址耳高、聯(lián)系方式扎瓶、售賣產(chǎn)品類型、銷售量等內(nèi)容的賣家信息表sellers
泌枪,在建表的同時概荷,為該表添加由賣家id號和產(chǎn)品類型組成的聯(lián)合主鍵,并在銷售量上創(chuàng)建索引碌燕。mysql> create table sellers -> ( -> s_id int not null auto_increment, -> s_name char(20) not null, -> s_address char(50) null, -> s_contact char(20) null, -> s_product_type int(5) not null, -> s_sales int null, -> primary key(s_id, s_product_type), -> index index_sales(s_sales) -> ); Query OK, 0 rows affected (0.02 sec)
使用ALTER TABLE語句創(chuàng)建
修改表的同時為該表添加索引:
mysql> alter table mysql_test.sellers -> add index index_contact(s_contact);
修改表的同時為該表添加主鍵:
mysql> alter table temp -> add primary key(t_id);
修改表時為該表添加唯一性索引:
mysql> alter table mysql_test.sellers -> add unique index index_address(s_address);
修改表時為該表添加外鍵:
mysql> alter table temp -> add foreign key(s_id) references sellers(s_id);
-
索引的查看:使用SHOW INDEX語句
show index from sellers in mysql_test;
-
索引的刪除:
使用DROP INDEX [ON]
drop index index_contact on mysql_test.sellers;
使用ALTER TABLE語句
選用
DROP PRIMARY KEY
子句用于刪除表中的主鍵误证,由于一個表中只有一個主鍵继薛,其也是一個索引:mysql> alter table mysql_test.temp -> drop primary key;
選用
DROP INDEX
子句刪除各種類型的索引:mysql> alter table mysql_test.sellers -> drop index index_address;
選用
DROP FOREIGN KEY
子句用于刪除外鍵:mysql> alter table mysql_test.temp -> drop foreign key temp_ibfk_1;
4. 數(shù)據(jù)更新
1. 插入數(shù)據(jù)
-
使用INSERT...VALUES語句插入單行或多行元組數(shù)據(jù)
INSERT [INTO] table_name [(column_name, ...)] {VALUE | VALUES} ({expr | DEFAULT}, ...), (), ...
使用
INSERT VALUES
語句向數(shù)據(jù)庫mysql_test
的表customers
中插入這樣一行完整數(shù)據(jù):(901,張山雷厂,F(xiàn)惋增,北京市,朝陽區(qū))mysql> insert into mysql_test.customers -> value ('zhangshan', 901, 'f', 'beijing', 'chaoyang');
使用
INSERT VALUES
語句向數(shù)據(jù)庫mysql_test
的表customers
中插入這樣一行數(shù)據(jù)改鲫,要求該數(shù)據(jù)目前只用明確給出c_name
和c_city
的信息诈皿,即“李四” “武漢”,而c_id
由系統(tǒng)自動生成像棘,c_sex
選用默認值稽亏,另外c_address
的值暫不確定,可不用指定缕题。mysql> insert into mysql_test.customers -> values ('lisi', 0, default, 'wuhan', null);
-
使用INSERT...SET語句插入部分列值數(shù)據(jù)
INSERT [INTO] table_name SET column_name = {expr | DEFAULT}, ...
使用
INSERT VALUES
語句向數(shù)據(jù)庫mysql_test
的表customers
中插入數(shù)據(jù):名為李四截歉,城市武漢,性別默認mysql> insert into mysql_test.customers -> set c_name = 'lisi', c_city = 'wuhan', c_sex = default;
-
INSERT...SELECT語句插入子查詢數(shù)據(jù)
INSERT [INTO] table_name [(column_name, ...)] SELECT ... //例 mysql> insert into mysql_test.customers -> select * from mysql_test.temp_customers;
2. 刪除數(shù)據(jù)
使用DELETE語句刪除一行或多行數(shù)據(jù)
DELETE FROM table_name
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
使用DELETE
語句刪除數(shù)據(jù)庫mysql_test
的表customers
中客戶名為lisi
的信息:
mysql> delete from mysql_test.customers
-> where c_name = 'lisi';
3. 修改數(shù)據(jù)
使用UPDATE語句修改更新一個表中的數(shù)據(jù)
UPDATE table_name
SET column_name1 = {expr | default}, [column_name2 = {expr | default}], ...
[WHERE where_condition]
[ORDER BY...]
[LIMIT row_count]
使用UPDATE
語句刪除數(shù)據(jù)庫mysql_test
的表customers
中姓名為zhangshan
的客戶的地址更新為wuhan
:
mysql> update mysql_test.customers
-> set c_address = 'wuhan'
-> where c_name = 'zhangshan';
5. 數(shù)據(jù)查詢
1. SELECT語句
SELECT
[ALL | DISTINCT | DISTINCTROW]
select_expr, [select_expr...]
FROM table_references
[WHERE where_condition]
[GROUP BY {column_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]]
[HAVING where_condition]
[ORDER BY {column_name | expr | position} [ASC | DESC], ...]
[LIMIT {[offset] row_count | row_count OFFSET offset}]
子句 | 說明 | 是否必須使用 |
---|---|---|
SELECT | 要返回的列或表達式 | 否 |
FROM | 從中檢索數(shù)據(jù)的表 | 僅在從表檢索數(shù)據(jù)時會用 |
WHERE | 行級過濾 | 否 |
GROUP BY | 分組說明 | 僅在按組計算聚合時使用 |
HAVING | 組級過濾 | 否 |
ORDER BY | 輸出排序順序 | 否 |
LIMIT | 要檢索的行數(shù) | 否 |
2. 列的選擇與指定
-
選擇指定的列
查詢數(shù)據(jù)庫
mysql_test
的表customers
中各個客戶的姓名烟零、性別和住址信息mysql> select c_id, c_name -> form mysql_test.customers;
-
選擇全部的信息
查詢數(shù)據(jù)庫
mysql_test
的表customers
中各個客戶的所有信息mysql> select * from mysql_test.customers;
-
定義并使用列的別名
column_name [AS] column_alias //例 mysql> select c_name, c_address as dizhi, c_contact -> from mysql_test.customers;
-
替換查詢結(jié)果集中的數(shù)據(jù)
CASE WHEN 條件1 THEN 表達式1 WHEN 條件2 THEN 表達式2 ... ELSE 表達式 END [AS] column_alias
查詢數(shù)據(jù)庫
mysql_test
的表customers
中客戶的c_name
列和c_sex
列瘪松,要求判斷結(jié)果集中c_sex
列的值,如果該列的值為m
锨阿,則顯示輸出nan
宵睦,否則為nv
,同時在結(jié)果集的顯示中將c_sex
列用xingbie
標注:mysql> select c_name, -> case -> when c_sex = 'm' then 'nan' -> else 'nv' -> end as 'xingbie' -> from mysql_test.customers;
-
計算列值
查詢數(shù)據(jù)庫
mysql_test
的表customers
中每個客戶的c_name
列墅诡,c_sex
列壳嚎,以及對c_id
列加上數(shù)字100
后的值:mysql> select c_id + 100, c_name, c_sex -> from mysql_test.customers;
-
聚合函數(shù)
函數(shù)名 說明 COUNT 求組中項數(shù),返回INT類型整數(shù) MAX 求最大值 MIN 求最小值 SUM 返回表達式中所有值的和 AVG 求組中值的平均值 STD或STDDEV 返回給定表達式中所有值的標準值 VARIANCE 返回給定表達式中所有值的方差 GROUP_CONCAT 返回由屬于一組的列值連接組合而成的結(jié)果 BIT_AND 邏輯與 BIT_OR 邏輯或 BIT_XOR 邏輯異或
3. FROM子句與多表連接查詢
-
交叉連接末早,又稱笛卡爾積
mysql> SELECT * FROM table1 CROSS JOIN table2; //或 mysql> SELECT * FROM table1, table2;
-
內(nèi)連接
SELECT some_column FROM table1 INNER JOIN table2 ON some_condition;
根據(jù)學(xué)生基本信息登記表
tb_student
和學(xué)生成績表tb_score
烟馅,使用內(nèi)連接查詢每個學(xué)生及其選課成績的詳細信息:mysql> select * -> from tb_student inner join tb_score -> on tb_student.stuendtNO = tb_score.studentNO;
-
外連接
- 左外連接:在FROM子句中使用關(guān)鍵字LEFT OUTER JOIN或LEFT JOIN
- 右外連接:在FROM子句中使用關(guān)鍵字RIGHT OUTER JOIN或RIGHT JOIN
根據(jù)學(xué)生基本信息登記表
tb_student
和學(xué)生成績表tb_score
,使用內(nèi)連接查詢每個學(xué)生及其選課成績的詳細信息:mysql> select * -> from tb_student left join tb_score -> on tb_student.stuendtNO = tb_score.studentNO;
4. WHERE子句與條件查詢
-
比較運算
在數(shù)據(jù)庫
mysql_test
的表customers
中查找所有男性客戶的信息:mysql> select * from mysql_test.customers -> where c_sex = 'm';
-
判定范圍
-
當(dāng)查詢的過濾條件被限定在值的某個范圍時然磷,可以使用關(guān)鍵字BETWEEN:
expression [NOT] BETWEEN expression1 AND expression2;
在數(shù)據(jù)庫
mysql_test
的表customers
中郑趁,查詢客戶id號在900
到905
之間的客戶信息:mysql> select * from mysql_test.customers -> where c_id between 900 and 905;
-
使用關(guān)鍵字IN,可以指定一個值的枚舉表姿搜,該表中會列出所有可能的值:
expression IN (expression [..., n]);
查詢id為901穿撮,904,905的客戶信息:
mysql> select * from mysql_test.customers -> where c_id in (901, 904, 905);
-
判定空值
expression IS [NOT] NULL;
在數(shù)據(jù)庫
mysql_test
的表customers
中痪欲,查詢聯(lián)系方式為空的客戶姓名:mysql> select c_name from mysql_test.customers -> where c_contact is null;
-
子查詢
- 表子查詢
- 行子查詢
- 列子查詢
- 標量子查詢
-
結(jié)合關(guān)鍵字IN使用的子查詢
主要用于判定一個給定值是否存在于子查詢的結(jié)果集中:
expression [NOT] IN (subquery);
查詢?nèi)我馑x課程成績高于80分的學(xué)生的學(xué)號和姓名:
mysql> select s_no, s_name from mysql_test.t_stu -> where s_no in -> ( -> select s_no from mysql_test.t_score -> where score > 80 -> );
-
結(jié)合比較運算符使用的子查詢
expression {= | < | <= | > | >= | != | <> | <=>} {ALL | SOME | ANY} (subquery)
-
結(jié)合關(guān)鍵字EXISTS使用的子查詢
子查詢的結(jié)果集不為空卓缰,則返回TRUE锦聊,否則返回FALSE
EXISTS (subquery)
-
5. GROUP BY子句與分組查詢
/*
column_name:指定用于分組的選擇列
expr:指定用于分組的表達式
position:指定用于分組的列在select語句結(jié)果集中的位置肠套,通常是一個正整數(shù)
ASC/DESC:排序方式嗽冒,默認asc
WITH ROLLUP:指定在結(jié)果集中不僅包含由group by子句分組后的數(shù)據(jù)行,還包含各分組的匯總行,可以得到每個分組以及每個分組級別的值
*/
GROUP BY {column_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]
在數(shù)據(jù)庫mysql_test
的表customers
中獲取一個數(shù)據(jù)結(jié)果集瞬沦,要求該結(jié)果集中分別包含每個相同地址的男性客戶人數(shù)和女性客戶人數(shù):
mysql> select c_address, c_sex, count(*) as 'renshu'
-> from mysql_test.customers
-> group by c_address, c_sex;
在數(shù)據(jù)庫mysql_test
的表customers
中獲取一個數(shù)據(jù)結(jié)果集太伊,要求該結(jié)果集中分別包含每個相同地址的男性客戶人數(shù)和女性客戶人數(shù),總?cè)藬?shù)以及客戶的總?cè)藬?shù):
mysql> select c_address, c_sex, count(*) as 'renshu'
-> from mysql_test.customers
-> group by c_address, c_sex
-> with rollup;
6. HAVING子句
HAVING where_condition
HAVING子句 | VS | WHERE子句 |
---|---|---|
過濾分組 | 過濾數(shù)據(jù)行 | |
可以包含聚合函數(shù) | 不可以包含聚合函數(shù) | |
在數(shù)據(jù)分組后進行過濾 | 在數(shù)據(jù)分組前進行過濾 |
在數(shù)據(jù)庫mysql_test
的表customers
中查找一類客戶信息逛钻,要求在返回的結(jié)果集中僚焦,列出相同客戶地址中滿足客戶人數(shù)少于3的所有客戶性別及其對應(yīng)地址:
mysql> select c_address, c_sex
-> from mysql_test.customers
-> group by c_address, c_sex
-> having count(*) <= 3;
7. ORDER BY子句
ORDER BY {column_name | expr | position} [ASC | DESC], ...
ORDER BY 子句 | VS | GROUP BY 子句 |
---|---|---|
排序產(chǎn)生的輸出 | 分組行,但輸出可能不是分組的順序 | |
任意列都可以使用 | 只可能使用選擇列或表達式列 | |
不一定需要 | 若與聚合函數(shù)一起使用列或表達式曙痘,則必須使用 |
在數(shù)據(jù)庫mysql_test
的表customers
中依次按照客戶姓名和地址的降序方式輸出客戶的姓名和性別:
mysql> select c_name, c_sex from mysql_test.customers
-> order by c_name desc, c_address desc;
8. LIMIT子句
使用LIMIT子句限制被SELECT語句返回的行數(shù)
/*
offset:可選項芳悲,默認0。指定返回數(shù)據(jù)的第一行在select語句結(jié)果集中的偏移量边坤,必須是非負的整數(shù)常量
row_count:指定返回數(shù)據(jù)的行數(shù)名扛,必須是非負的整數(shù)常量
row_count OFFSET offset:從offset+1行開始,取row_count行
*/
LIMIT {[offset] row_count | row_count OFFSET offset}
在數(shù)據(jù)庫mysql_test
的表customers
中查找從第2位開始的3位客戶的id號和姓名:
mysql> select c_id, c_name from mysql_test.customers
-> limit 1, 3;
//或
mysql> select c_id, c_name from mysql_test.customers
-> limit 3 offset 1;
6. 視圖
1. 視圖的定義
視圖是數(shù)據(jù)庫中的一個對象茧痒,它是數(shù)據(jù)庫管理系統(tǒng)提供給用戶的以多種角度觀察數(shù)據(jù)庫中數(shù)據(jù)的一種機制肮韧。
視圖不是數(shù)據(jù)庫中真實的表,而是一張?zhí)摂M的表旺订,其自身并不存儲數(shù)據(jù)弄企。
2. 使用視圖的優(yōu)點:
- 集中分散數(shù)據(jù)
- 簡化查詢語句
- 重用sql語句
- 保護數(shù)據(jù)安全
- 共享所需數(shù)據(jù)
- 更改數(shù)據(jù)格式
3. 創(chuàng)建視圖
使用CREATE VIEW創(chuàng)建視圖
/*
view_name:指定視圖的名稱
column_list:可選項,為每個列指定名稱
select_statement:指定select語句
[WITH [CASCADED | LOCAL] CHECK OPTION]:可選項区拳,指定在可更新視圖上所進行的修改都需要符select_statement中指定的限制條件
*/
CREATE [OR REPLACE] VIEW view_name [(column_list)]
AS select_statement
[WITH [CASCADED | LOCAL] CHECK OPTION]
在數(shù)據(jù)庫mysql_test
的創(chuàng)建視圖customers_view
拘领,要求該視圖包含客戶信息表customers
中所有男客戶的信息,并且要求保證今后對該視圖數(shù)據(jù)的修改都必須符合客戶性別為男性這個條件:
create or replace view mysql_test.customers_view
as select * from mysql_test.customers where c_sex = 'm'
with check option;
4. 刪除視圖
DROP VIEW [IF EXISTS] view_name [, view_name, ...]
[RESTRICT CASCADE]
5. 修改視圖定義
使用ALTER VIEW語句對已有視圖的定義(結(jié)構(gòu))進行修改
ALTER VIEW view_name [column_list]
AS select_statement
[WITH [CASCADED | LOACL] CHECK OPTION]
6. 查看視圖定義
使用SHOW CREATE VIEW語句查看已有視圖的定義(結(jié)構(gòu))
SHOW CREATE VIEW view_name;
7. 更新視圖數(shù)據(jù)
-
使用INSERT語句通過視圖向基本表插入數(shù)據(jù)
在數(shù)據(jù)庫
mysql_test
中劳闹,向視圖customers_view
插入記錄:(909,‘zhouming’洽瞬,‘wuhan’本涕,‘hongshanqu’):INSERT INTO mysql_test.customers_view VALUES (909, 'zhouming', 'wuhan', 'hongshanqu');
-
使用UPDATE語句通過視圖修改基本表的數(shù)據(jù)
將視圖
customers_view
中所有c_address
列更新為shanghai
UPDATE mysql_test.customers_view SET c_address = 'shanghai';
-
使用DELETE語句通過視圖刪除基本表的數(shù)據(jù)
刪除
customers_view
中姓名為zhouming
的客戶信息DELETE FROM mysql_test.customers_view WHERE c_name = ‘zhouming’;
8. 查詢視圖數(shù)據(jù)
在視圖customers_view
中客戶id為905號的客戶姓名及其地址:
SELECT c_name, c_address
FROM mysql_test.customers_view
WHERE c_id = 905;