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

ค้นหาคอลัมน์ว่ามีอยู่ในตารางไหนบ้างใน MySQL

การค้นหาชื่อคอลัมน์ในทุกตารางของฐานข้อมูลปัจจุบัน

Query INFORMATION_SCHEMA.COLUMNS กรองด้วย table_schema = SCHEMA() และชื่อคอลัมน์ที่ต้องการ

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

SELECT table_name, column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = SCHEMA()
  AND column_name = 'anyColumnName';

ตัวอย่าง: ค้นหาคอลัมน์ EmployeeAge

mysql> SELECT table_name, column_name
    -> FROM INFORMATION_SCHEMA.COLUMNS
    -> WHERE table_schema = SCHEMA()
    -> AND column_name = 'EmployeeAge';

ผลลัพธ์ (ตัวอย่าง):

+---------------+-------------+
| TABLE_NAME    | COLUMN_NAME |
+---------------+-------------+
| demotable1153 | EmployeeAge |
| demotable1297 | EmployeeAge |
| demotable1303 | EmployeeAge |
| ...           | ...         |
+---------------+-------------+
12 rows in set (0.00 sec)

ยืนยันด้วย DESC

mysql> DESC demotable1153;
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| EmployeeId   | int(11)     | NO   | PRI | NULL    | auto_increment |
| EmployeeName | varchar(40) | YES  | MUL | NULL    |                |
| EmployeeAge  | int(11)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+

ประโยชน์: ช่วยหาว่าคอลัมน์ใดถูกใช้ในตารางไหนบ้าง เหมาะสำหรับการบำรุงรักษาสคีมา