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

แสดงคอลัมน์เฉพาะบางคอลัมน์จาก SHOW COLUMNS ใน MySQL


คำสั่งหลัก

ใช้ SHOW COLUMNS FROM table WHERE Field NOT IN (...) เพื่อกรองคอลัมน์ที่ไม่ต้องการ

รูปแบบคำสั่ง

SHOW COLUMNS FROM yourTableName WHERE Field NOT IN ('col1', 'col2', ...);

ตัวอย่างครบถ้วน

1. สร้างตาราง

mysql> create table excludeCertainColumnsDemo 
    -> ( 
    -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    -> StudentName varchar(100), 
    -> StudentAge int, 
    -> StudentMarks int, 
    -> StudentAddress varchar(200) 
    -> ); 
Query OK, 0 rows affected (0.50 sec)

2. ดูโครงสร้างทั้งหมด (DESC)

mysql> desc excludeCertainColumnsDemo;
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| StudentId      | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentName    | varchar(100) | YES  |     | NULL    |                |
| StudentAge     | int(11)      | YES  |     | NULL    |                |
| StudentMarks   | int(11)      | YES  |     | NULL    |                |
| StudentAddress | varchar(200) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+

3. แสดงคอลัมน์ยกเว้น StudentAge และ StudentMarks

mysql> SHOW COLUMNS FROM excludeCertainColumnsDemo WHERE Field NOT IN ('StudentAge', 'StudentMarks');
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| StudentId      | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentName    | varchar(100) | YES  |     | NULL    |                |
| StudentAddress | varchar(200) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+

วิธีอื่น: ใช้ INFORMATION_SCHEMA (ยืดหยุ่นกว่า)

SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_KEY, COLUMN_DEFAULT, EXTRA
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'yourDatabase' 
  AND TABLE_NAME = 'yourTable'
  AND COLUMN_NAME NOT IN ('StudentAge', 'StudentMarks');

กรองแบบ Pattern (LIKE)

-- แสดงเฉพาะคอลัมน์ที่ขึ้นต้นด้วย 'Student'
SHOW COLUMNS FROM excludeCertainColumnsDemo WHERE Field LIKE 'Student%';

-- ซ่อนคอลัมน์ที่ลงท้ายด้วย 'Marks'
SHOW COLUMNS FROM excludeCertainColumnsDemo WHERE Field NOT LIKE '%Marks';

สรุป: WHERE clause ใน SHOW COLUMNS ทำให้กรองคอลัมน์ได้ง่าย ไม่ต้อง query INFORMATION_SCHEMA เอง