创建 MySQL 查询以从现有表创建一个表?
你可以使用创建表命令从现有表创建表。语法如下
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)
现在,我们使用创建表命令从现有表创建一个新表。查询如下
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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP