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

แสดงชื่อคอลัมน์ยกเว้นบางคอลัมน์ใน MySQL

ใช้ INFORMATION_SCHEMA.COLUMNS ร่วมกับ NOT IN เพื่อกรองคอลัมน์ที่ไม่ต้องการ

สร้างตารางตัวอย่าง

mysql> create table DemoTable780 ( 
    CustomerId int, 
    CustomerName varchar(100), 
    CustomerAge int, 
    CustomerCountryName varchar(100), 
    isMarried tinyint(1) ); 
Query OK, 0 rows affected (0.47 sec)

คิวรีดึงชื่อคอลัมน์ยกเว้น CustomerId และ CustomerCountryName

mysql> select group_concat(column_name) 
from `information_schema`.`COLUMNS` m 
where table_schema = 'web' 
and table_name = 'DemoTable780' 
and column_name not in ('CustomerId','CustomerCountryName') 
group by table_schema,table_name;
+------------------------------------+
| group_concat(column_name)          |
+------------------------------------+
| CustomerName,CustomerAge,isMarried |
+------------------------------------+
1 row in set (0.01 sec)

ประโยชน์: สร้างคิวรีไดนามิกได้โดยไม่ต้องพิมพ์ชื่อคอลัมน์ทั้งหมด