Computer >> Máy Tính >  >> Lập trình >> MySQL

Làm thế nào để tạo một lệnh “tạo bảng” dựa trên một bảng hiện có trong MySQL?

Bạn có thể tạo lệnh tạo bảng dựa trên bảng hiện có trong MySQL với sự trợ giúp của lệnh SHOW CREATE.

Cú pháp như sau

SHOW CREATE TABLE yourTableName;

Để hiểu cú pháp trên, chúng ta hãy tạo một bảng. Truy vấn để tạo bảng như sau

mysql> create table StudentInformation
   - > (
   - > StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > StudentName varchar(20),
   - > StudentAge int DEFAULT 18,
   - > StudentRollNo int,
   - > StudentAddress varchar(200),
   - > StudentMarks int,
   - > StudentDOB datetime,
   - > StudentAdmissionDate datetime
   - > );
Query OK, 0 rows affected (0.54 sec)

Bây giờ, hãy sử dụng cú pháp trên để tạo lệnh tạo bảng.

Truy vấn như sau

mysql> SHOW CREATE TABLE StudentInformation;

Sau đây là kết quả

+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| StudentInformation | CREATE TABLE `studentinformation` (
`StudentId` int(11) NOT NULL AUTO_INCREMENT,
`StudentName` varchar(20) DEFAULT NULL,
`StudentAge` int(11) DEFAULT '18',
`StudentRollNo` int(11) DEFAULT NULL,
`StudentAddress` varchar(200) DEFAULT NULL,
`StudentMarks` int(11) DEFAULT NULL,
`StudentDOB` datetime DEFAULT NULL,
`StudentAdmissionDate` datetime DEFAULT NULL,
PRIMARY KEY (`StudentId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+--------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.04 sec)