Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การตรวจสอบการเปลี่ยนแปลงโครงสร้างฐานข้อมูล MySQL (Schema Changes)

เพื่อตรวจสอบว่าโครงสร้างฐานข้อมูล (Schema) เปลี่ยนแปลงหรือไม่ ใช้คำสั่ง SHOW CREATE TABLE เพื่อดู DDL ของตาราง

สร้างตารางตัวอย่าง

mysql> create table DemoTable ( 
    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    StudentName varchar(40), 
    StudentAge int, 
    StudentMarks int ); 
Query OK, 0 rows affected (0.76 sec)

ดูโครงสร้างตาราง (ก่อนเปลี่ยนแปลง)

mysql> show create table DemoTable;
+---------------+------------------------------------------------------------------+
| Table         | Create Table                                                     |
+---------------+------------------------------------------------------------------+
| DemoTable     | CREATE TABLE `DemoTable` (`StudentId` int(11) NOT NULL AUTO_INCREMENT, 
`StudentName` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, 
`StudentAge` int(11) DEFAULT NULL, 
`StudentMarks` int(11) DEFAULT NULL, 
PRIMARY KEY (`StudentId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
+---------------+------------------------------------------------------------------+
1 row in set (0.06 sec)

เปลี่ยนแปลงโครงสร้าง (เพิ่มคอลัมน์)

mysql> alter table DemoTable add column StudentCountryName varchar(20); 
Query OK, 0 rows affected (0.65 sec)
Records: 0  Duplicates: 0  Warnings: 0

ดูโครงสร้างตาราง (หลังเปลี่ยนแปลง)

mysql> show create table DemoTable;
+---------------+------------------------------------------------------------------+
| Table         | Create Table                                                     |
+---------------+------------------------------------------------------------------+
| DemoTable     | CREATE TABLE `DemoTable` (`StudentId` int(11) NOT NULL AUTO_INCREMENT, 
`StudentName` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, 
`StudentAge` int(11) DEFAULT NULL, 
`StudentMarks` int(11) DEFAULT NULL, 
`StudentCountryName` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL, 
PRIMARY KEY (`StudentId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |
+---------------+------------------------------------------------------------------+
1 row in set (0.00 sec)

วิธีตรวจสอบการเปลี่ยนแปลงแบบอัตโนมัติ

  • Version Control: Export schema ด้วย mysqldump --no-data และ commit ไว้ใน Git
  • Schema Comparison Tools: ใช้เครื่องมือเช่น pt-table-sync, SchemaSpy, Liquibase, Flyway
  • Triggers: สร้าง Trigger บน information_schema (ซับซ้อน ไม่แนะนำ)
  • Binary Log: ตรวจสอบ binlog สำหรับ DDL statements

คิวรี่ตรวจสอบคอลัมน์ที่เพิ่งเพิ่ม

SELECT * FROM information_schema.columns 
WHERE table_schema = 'your_db' AND table_name = 'DemoTable' 
AND create_time > DATE_SUB(NOW(), INTERVAL 1 HOUR);

แนวทางปฏิบัติที่ดี

ใช้ Database Migration Tool (Flyway, Liquibase) จัดการ Schema Versioning แทนการตรวจสอบย้อนหลัง