如何在MySQL中轻松地“从视图创建表”语法?
您可以使用createtableselect语法从视图创建表。语法如下-
CREATE TABLE yourTableName AS SELECT yourColumnName1,yourColumnName2,yourColumnName3,........N from yourViewName;
要运行上述查询,首先需要创建一个表,然后需要在该表上创建一个视图。之后,运行查询。
首先,您需要创建一个表。创建表的查询如下-
mysql> create table StuedntInformation -> ( -> Id int, -> Name varchar(100) -> );
上面,我们创建了一个表。之后,您需要创建一个视图。创建视图的查询如下-
mysql> CREATE VIEW view_Student AS SELECT Id,Name from StuedntInformation;
现在,我创建了一个名为“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; 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)