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

MySQL: เรียงลำดับตารางตามชื่อด้วย SHOW TABLES และ INFORMATION_SCHEMA

คำสั่ง SHOW TABLES แสดงรายการตารางในฐานข้อมูล แต่ไม่รองรับการเรียงลำดับโดยตรง เพื่อเรียงลำดับชื่อตาราง ต้องใช้ INFORMATION_SCHEMA.TABLES ร่วมกับ ORDER BY แทน

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

SELECT table_name 
FROM information_schema.tables 
WHERE table_type = 'BASE TABLE' 
  AND table_schema = 'your_database_name'
ORDER BY table_name DESC;
  • table_type = 'BASE TABLE' - กรองเฉพาะตารางทั่วไป (ไม่รวม view)
  • table_schema - ระบุชื่อฐานข้อมูล
  • ORDER BY table_name ASC|DESC - เรียงจาก A-Z หรือ Z-A

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

ฐานข้อมูล sample มีตารางดังนี้:

mysql> SHOW TABLES;
+--------------------------+
| Tables_in_sample         |
+--------------------------+
| blobsizedemo             |
| insert_prevent           |
| insertrecord_selecttable |
| insertrecordprevent      |
| mytable                  |
| newlinedemo              |
| notequaloperator         |
| sumofeverydistinct       |
| yourtable                |
+--------------------------+

เรียงลำดับชื่อตารางจาก Z-A (DESC)

SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE' 
  AND table_schema = 'sample'
ORDER BY table_name DESC;

ผลลัพธ์:

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

เรียงลำดับจาก A-Z (ASC)

SELECT table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE' 
  AND table_schema = 'sample'
ORDER BY table_name ASC;

วิธีนี้ให้ความยืดหยุ่นมากกว่า SHOW TABLES เพราะสามารถกรอง เลือกคอลัมน์ และเรียงลำดับได้ตามต้องการ