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

ดึงชื่อคอลัมน์ของตาราง MySQL

วิธีดูชื่อคอลัมน์ของตารางใน MySQL

ใช้คำสั่ง SHOW COLUMNS หรือ DESCRIBE (ย่อได้เป็น DESC)

SHOW COLUMNS FROM yourTableName;
DESC yourTableName;

ตัวอย่างการใช้งาน

สร้างตาราง:

mysql> create table DemoTable (
    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    StudentFirstName varchar(20),
    StudentLastName varchar(20),
    StudentAge int,
    StudentAddress varchar(200)
);

ดูโครงสร้างตาราง:

mysql> show columns from DemoTable;
+------------------+--------------+------+-----+---------+----------------+
| Field            | Type         | Null | Key | Default | Extra          |
+------------------+--------------+------+-----+---------+----------------+
| StudentId        | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentFirstName | varchar(20)  | YES  |     | NULL    |                |
| StudentLastName  | varchar(20)  | YES  |     | NULL    |                |
| StudentAge       | int(11)      | YES  |     | NULL    |                |
| StudentAddress   | varchar(200) | YES  |     | NULL    |                |
+------------------+--------------+------+-----+---------+----------------+

คำอธิบายคอลัมน์ผลลัพธ์:

  • Field - ชื่อคอลัมน์
  • Type - ชนิดข้อมูล
  • Null - YES = รับ NULL ได้, NO = NOT NULL
  • Key - PRI = Primary Key, UNI = Unique, MUL = Index (Non-unique)
  • Default - ค่าเริ่มต้น
  • Extra - ข้อมูลเพิ่มเติม (auto_increment, on update CURRENT_TIMESTAMP, ฯลฯ)

ทางเลือกอื่น (Programmatic): ใช้ INFORMATION_SCHEMA.COLUMNS (ดูรายละเอียดในบทความ ID 1004073581)