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

MySQL: ไวยากรณ์ NOT LIKE ที่ถูกต้องสำหรับ SHOW TABLES

คำสั่ง SHOW TABLES ใน MySQL รองรับการกรองด้วย WHERE และ LIKE/NOT LIKE แต่ต้องใช้รูปแบบคอลัมน์ที่ถูกต้อง

รูปแบบคำสั่งที่ถูกต้อง

SHOW TABLES 
WHERE `Tables_in_your_database_name` NOT LIKE 'pattern%';
  • ชื่อคอลัมน์ใน WHERE ต้องเป็น Tables_in_<database_name> (รวม backtick)
  • ชื่อฐานข้อมูลต้องตรงกับที่ใช้งานอยู่ (current database)

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

1. ใช้ฐานข้อมูล sample และดูตารางทั้งหมด

USE sample;
SHOW TABLES;

ผลลัพธ์:

+--------------------------+
| Tables_in_sample         |
+--------------------------+
| blobsizedemo             |
| insert_prevent           |
| insertrecord_selecttable |
| insertrecordprevent      |
| mytable                  |
| newlinedemo              |
| notequaloperator         |
| sumofeverydistinct       |
| yourtable                |
+--------------------------+

2. กรองตารางที่ชื่อ ไม่ขึ้นต้นด้วย 'insert'

SHOW TABLES 
WHERE `Tables_in_sample` NOT LIKE 'insert%';

ผลลัพธ์:

+--------------------+
| Tables_in_sample   |
+--------------------+
| blobsizedemo       |
| mytable            |
| newlinedemo        |
| notequaloperator   |
| sumofeverydistinct |
| yourtable          |
+--------------------+

ตาราง insert_prevent, insertrecord_selecttable, insertrecordprevent ถูกกรองออก

กรณีใช้ LIKE (ตรงข้าม)

SHOW TABLES WHERE `Tables_in_sample` LIKE 'insert%';

จะได้เฉพาะตารางที่ขึ้นต้นด้วย 'insert' 3 ตาราง

ข้อสังเกตสำคัญ

  • SHOW TABLES ไม่รองรับ ORDER BY โดยตรง
  • หากต้องการเรียงลำดับ ใช้ SELECT table_name FROM information_schema.tables ... ORDER BY table_name
  • ชื่อคอลัมน์ Tables_in_... เป็นชื่อคงที่ของ MySQL สำหรับ SHOW TABLES output

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

SELECT table_name 
FROM information_schema.tables 
WHERE table_schema = 'sample' 
  AND table_type = 'BASE TABLE'
  AND table_name NOT LIKE 'insert%'
ORDER BY table_name;

วิธีนี้:

  • รองรับ ORDER BY
  • กรอง table_type ได้ (BASE TABLE / VIEW)
  • Select คอลัมน์อื่นได้ (ENGINE, TABLE_ROWS, CREATE_TIME, etc.)
  • ทำงานเหมือนกันทุก MySQL Version

สรุป

ใช้ SHOW TABLES WHERE \`Tables_in_db\` NOT LIKE 'pattern%' สำหรับกรองเร็ว แต่ INFORMATION_SCHEMA ยืดหยุ่นกว่าสำหรับรายงานและการพัฒนา