Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Tạo câu lệnh CREATE TABLE từ bảng có sẵn trong MySQL

Tóm tắt

Dùng SHOW CREATE TABLE ten_bang để lấy câu lệnh CREATE TABLE đầy đủ (kể cả engine, charset, collation, partition, v.v.).

Cú pháp

SHOW CREATE TABLE ten_bang;

Ví dụ

1. Tạo bảng phức tạp

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
);

2. SHOW CREATE TABLE

SHOW CREATE TABLE StudentInformation;

3. Kết quả (cột Create Table)

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

Ứng dụng

  • Backup schema, migration, documentation.
  • Clone bảng: CREATE TABLE new_table LIKE old_table (chỉ cấu trúc, không data).
  • So sánh schema giữa môi trường dev/staging/prod.
  • Tự động sinh code ORM/entity.

Lưu ý

  • Kết quả có backtick, charset, collation, engine – có thể chạy trực tiếp để tạo lại bảng.
  • AUTO_INCREMENT value không được bao gồm (dùng SHOW TABLE STATUS để xem).
  • VIEW dùng SHOW CREATE VIEW.