在 MySQL 中获取表列名称?

2022-08-30 05:56:04

有没有办法使用PHP在MySQL中获取表的列名?


答案 1

您可以使用 DESCRIBE

DESCRIBE my_table;

或者在较新版本中,您可以使用INFORMATION_SCHEMA

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

或者,您可以使用“显示列”

SHOW COLUMNS FROM my_table;

或者,在一行中用逗号获取列名:

SELECT group_concat(COLUMN_NAME)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';

答案 2

以下 SQL 语句几乎等效:

SELECT COLUMN_NAME
  FROM INFORMATION_SCHEMA.COLUMNS
 WHERE table_name = 'tbl_name'
  [AND table_schema = 'db_name']
  [AND column_name LIKE 'wild']

SHOW COLUMNS
FROM tbl_name
[FROM db_name]
[LIKE 'wild']

参考:INFORMATION_SCHEMA列


推荐