如何在 MySQL 中轻松使用“从视图创建表”语法?
您可以使用 create table select 语法从视图创建表。语法如下:
CREATE TABLE yourTableName AS SELECT yourColumnName1,yourColumnName2,yourColumnName3,........N from yourViewName;
要运行以上查询,您需要先创建一个表,然后在该表上创建一个视图。之后再运行查询。
首先,您需要创建一个表。创建表的查询如下:
mysql> create table StuedntInformation -> ( -> Id int, -> Name varchar(100) -> ); Query OK, 0 rows affected (0.54 sec)
在上面,我们创建了一个表。之后,您需要创建一个视图。创建视图的查询如下:
mysql> CREATE VIEW view_Student AS SELECT Id,Name from StuedntInformation; Query OK, 0 rows affected (0.11 sec)
现在,我创建了一个名为“view_Student”的视图。使用 show 命令检查视图。
查询如下:
mysql> SHOW CREATE VIEW view_Student;
输出
+--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+ | View | Create View | character_set_client | collation_connection | +--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+ | view_student | CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`%` SQL SECURITY DEFINER VIEW `view_student` AS select `stuedntinformation`.`Id` AS `Id`,`stuedntinformation`.`Name` AS `Name` from `stuedntinformation` | utf8 | utf8_general_ci | +--------------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+ 1 row in set (0.00 sec)
我们将使用上述视图名称“view_Student”来创建一个表。以下是使用视图创建表的查询:
mysql> CREATE TABLE CreatingTableUsingViewStudent AS -> select Id,Name from view_Student; Query OK, 0 rows affected (0.50 sec) Records: 0 Duplicates: 0 Warnings: 0
现在,您可以使用 show 命令检查表的 DDL。查询如下:
mysql> show create table CreatingTableUsingViewStudent;
输出
+-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | CreatingTableUsingViewStudent | CREATE TABLE `creatingtableusingviewstudent` ( `Id` int(11) DEFAULT NULL, `Name` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci | +-------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec)
广告