摘要:在本教程中,您将学习如何使用 MySQL DROP VIEW
语句从数据库中删除视图。
MySQL DROP VIEW
语句简介
DROP VIEW
语句从数据库中完全删除视图。以下是DROP VIEW
语句的基本语法:
DROP VIEW [IF EXISTS] view_name;
Code language: SQL (Structured Query Language) (sql)
在此语法中,您可以在DROP VIEW
关键字后指定要删除的视图的名称。可选的IF EXISTS
选项仅在视图存在时有条件地删除该视图。
要在单个语句中删除多个视图,请使用以下语法:
DROP VIEW [IF EXISTS] view_name1 [,view_name2]...;
Code language: SQL (Structured Query Language) (sql)
在此语法中,您可以在 DROP VIEW 关键字后指定以逗号分隔的视图列表。
如果列表包含不存在的视图,则DROP VIEW
语句将失败并且不会删除任何视图。但是,如果使用IF EXISTS
选项, DROP VIEW
语句将为每个不存在的视图生成一个NOTE
。
请注意,在 MySQL 5.7 或更早版本中,如果存在任何不存在的视图,则DROP VIEW
将返回错误。然而,它放弃了现有的观点。
MySQL DROP VIEW 语句示例
让我们举一些使用DROP VIEW
语句的示例。
1) MySQL DROP VIEW – 删除视图示例
此语句根据customers
和payments
表创建一个名为customerPayments
的视图:
CREATE VIEW customerPayments
AS
SELECT
customerName,
SUM(amount) payment
FROM
customers
INNER JOIN payments
USING (customerNumber)
GROUP BY
customerName;
Code language: SQL (Structured Query Language) (sql)
此示例使用DROP VIEW
语句删除customerPayments
视图:
DROP VIEW IF EXISTS customerPayments;
Code language: SQL (Structured Query Language) (sql)
2) MySQL DROP VIEW
– 删除多个视图示例
此语句根据employees
和offices
表创建一个名为employeeOffices
的视图:
CREATE VIEW employeeOffices AS
SELECT
firstName, lastName, addressLine1, city
FROM
employees
INNER JOIN
offices USING (officeCode);
Code language: SQL (Structured Query Language) (sql)
以下语句使用DROP VIEW
语句删除两个视图employeeOffices
和eOffices
:
DROP VIEW employeeOffices, eOffices;
Code language: SQL (Structured Query Language) (sql)
MySQL 发出以下错误:
Error Code: 1051. Unknown table 'classicmodels.eoffices'
Code language: SQL (Structured Query Language) (sql)
让我们添加IF EXISTS
选项,如下所示:
DROP VIEW IF EXISTS employeeOffices, eOffices;
Code language: SQL (Structured Query Language) (sql)
MySQL 发出了警告:
1 warning(s): 1051 Unknown table 'classicmodels.eoffices'
Code language: SQL (Structured Query Language) (sql)
employeeOffices
视图保持不变。
此语句根据products
和productLines
表创建一个名为productCatalogs
的新视图:
CREATE VIEW productCatalogs AS
SELECT
productLine, productName, msrp
FROM
products
INNER JOIN
productLines USING (productLine);
Code language: SQL (Structured Query Language) (sql)
以下示例使用DROP VIEW
语句删除employeeOffices
和productCatalogs
视图:
DROP VIEW employeeOffices, productCatalogs;
Code language: SQL (Structured Query Language) (sql)
MySQL 完全删除了视图。
概括
- 使用
DROP VIEW
语句从数据库中删除一个或多个视图。 - 使用
IF EXISTS
选项有条件地删除视图(如果存在)。