MySQL 檢視
MySQL CREATE VIEW 語句
在 SQL 中,檢視是一個基於 SQL 語句結果集的虛擬表。
檢視包含行和列,就像一個真實表一樣。檢視中的欄位來自資料庫中的一個或多個真實表的欄位。
您可以向檢視新增 SQL 語句和函式,並以資料來自單個表的方式呈現資料。
檢視是使用 CREATE VIEW
語句建立的。
CREATE VIEW 語法
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
注意: 檢視始終顯示最新的資料!每次使用者查詢檢視時,資料庫引擎都會重新建立它。
MySQL CREATE VIEW 示例
以下 SQL 建立了一個顯示所有來自巴西的客戶的檢視
示例
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
We can query the view above as follows
示例
SELECT * FROM [Brazil Customers];
以下 SQL 建立了一個檢視,該檢視選擇 "Products" 表中價格高於平均價格的所有產品
示例
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
We can query the view above as follows
示例
SELECT * FROM [Products Above Average Price];
MySQL 更新檢視
可以使用 CREATE OR REPLACE VIEW
語句更新檢視。
CREATE OR REPLACE VIEW 語法
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The following SQL adds the "City" column to the "Brazil Customers" view
示例
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
MySQL 刪除檢視
使用 DROP VIEW
語句刪除檢視。
DROP VIEW 語法
DROP VIEW view_name;
The following SQL drops the "Brazil Customers" view (以下 SQL 語句刪除 "Brazil Customers" 檢視)
示例
DROP VIEW [Brazil Customers];