mysql 查询表的字段/列名; 查询字段/列名所在的表

查询表的字段/列名

  • 用 show 的方法
SHOW COLUMNS from database_name.table_name;

mysql> show columns from actor;
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| Field       | Type                 | Null | Key | Default           | Extra                       |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| actor_id    | smallint(5) unsigned | NO   | PRI | NULL              | auto_increment              |
| first_name  | varchar(45)          | NO   |     | NULL              |                             |
| last_name   | varchar(45)          | NO   | MUL | NULL              |                             |
| last_update | timestamp            | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
4 rows in set (0.00 sec)
  • 很多时候只需要查询列名,即上面例子的 field, 不需要具体信息。
SELECT
    COLUMN_NAME
FROM
    information_schema.COLUMNS
WHERE
    table_schema = 'database_name'
    AND table_name = 'table_name';

mysql> select column_name from information_schema.COLUMNS
    -> where table_schema = 'sakila' and table_name = 'actor';
+-------------+
| COLUMN_NAME |
+-------------+
| actor_id    |
| first_name  |
| last_name   |
| last_update |
+-------------+
4 rows in set (0.00 sec)

查询字段/列名所在的表

依然使用information_schema这个数据库的COLUMNS这个表。

SELECT 
    TABLE_NAME 
FROM
    information_schema.COLUMNS
WHERE
    column_name = 'XXXX';

注意,这样查询范围是节点上的所有database,如果指定数据库 ,像上面一样,在where条件中加上
table_schema的内容。

-- 没有指定数据库
mysql> select table_name, table_schema  from information_schema.columns where column_name = 'id';
+----------------------+--------------------+
| TABLE_NAME           | TABLE_SCHEMA       |
+----------------------+--------------------+
| COLLATIONS           | information_schema |
| INNODB_FOREIGN       | information_schema |
| INNODB_FOREIGN_COLS  | information_schema |
| PROCESSLIST          | information_schema |
| slave_relay_log_info | mysql              |
| slave_worker_info    | mysql              |
| customer_list        | sakila             |
| staff_list           | sakila             |
| employee             | test               |
| test_alter           | test               |
+----------------------+--------------------+
10 rows in set (0.01 sec)

-- 指定数据库
mysql> select table_name from information_schema.columns 
    -> where column_name = 'id' and table_schema = 'sakila' ;
+---------------+
| TABLE_NAME    |
+---------------+
| customer_list |
| staff_list    |
+---------------+
2 rows in set (0.00 sec)

以上。

发布了26 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Olivia_Vang/article/details/103173317