创建MySQL查询以从现有表创建表?
您可以使用CREATETABLE命令从现有表创建表。语法如下:
CREATE TABLE yourNewTableName LIKE yourOldTableName
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table ShowCreateTableCommand -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FirstName varchar(20), -> LastName varchar(20), -> Age int, -> TotalMarks int, -> PRIMARY KEY(Id) -> );
这是使用DESC命令描述表的查询。查询如下:
mysql> desc ShowCreateTableCommand;
以下是输出:
+------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+-------------+------+-----+---------+----------------+ | Id | int(11) | NO | PRI | NULL | auto_increment | | FirstName | varchar(20) | YES | | NULL | | | LastName | varchar(20) | YES | | NULL | | | Age | int(11) | YES | | NULL | | | TotalMarks | int(11) | YES | | NULL | | +------------+-------------+------+-----+---------+----------------+ 5 rows in set (0.11 sec)
这是检查表结构的查询:
mysql> show create table ShowCreateTableCommand\G
以下是输出:
*************************** 1. row *************************** Table: ShowCreateTableCommand Create Table: CREATE TABLE `showcreatetablecommand` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `FirstName` varchar(20) DEFAULT NULL, `LastName` varchar(20) DEFAULT NULL, `Age` int(11) DEFAULT NULL, `TotalMarks` int(11) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci 1 row in set (0.00 sec)
现在让我们使用CREATETABLE命令从现有表中创建一个新表。查询如下:
mysql> CREATE TABLE StudentInformationDemo LIKE ShowCreateTableCommand;
现在检查新表的结构是否与旧表的结构匹配:
mysql> show create table StudentInformationDemo\G
以下是输出:
*************************** 1. row *************************** Table: StudentInformationDemo Create Table: CREATE TABLE `studentinformationdemo` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `FirstName` varchar(20) DEFAULT NULL, `LastName` varchar(20) DEFAULT NULL, `Age` int(11) DEFAULT NULL, `TotalMarks` int(11) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci 1 row in set (0.00 sec)