建立 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)

更新於: 30-Jul-2019

377 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.