创建 MySQL 查询以从现有表创建表?
mysqlmysqli database
您可以使用 CREATE TABLE 命令从现有表创建表。语法如下:
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) -> ); Query OK, 0 rows affected (1.22 sec)
这是使用 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)
现在让我们使用 CREATE TABLE 命令从现有表创建新表。查询如下:
mysql> CREATE TABLE StudentInformationDemo LIKE ShowCreateTableCommand; Query OK, 0 rows affected (0.49 sec)
现在检查新表的结构是否与旧表结构匹配:
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)