获取视图中底层表的主键

get primary keys of underlaying tables in a view

我知道 show tablesshow columns from table TABLE_NAME 是我的主键(KeyPRI)。但是如何获取视图的主键或更具体的基础表的键?在这种情况下 show columns from VIEW_NAME 所有键值都是空的。

存在新的 INFORMATION_SCHEMA table 以将视图映射到基础 table(s)。它被称为 VIEW_TABLE_USAGE

mysql> create table mytable (id serial primary key);
Query OK, 0 rows affected (0.01 sec)

mysql> create view v as select * from mytable;
Query OK, 0 rows affected (0.00 sec)
    
mysql> select table_schema, table_name, column_name, ordinal_position
 from information_schema.view_table_usage 
 join information_schema.key_column_usage using (table_schema, table_name) 
 where table_name='mytable' and constraint_name='PRIMARY';
+--------------+------------+-------------+------------------+
| TABLE_SCHEMA | TABLE_NAME | COLUMN_NAME | ORDINAL_POSITION |
+--------------+------------+-------------+------------------+
| test2        | mytable    | id          |                1 |
+--------------+------------+-------------+------------------+

此 table 是 MySQL 8.0.13 中的新增功能。 如果您使用旧版本的 MySQL(或任何版本的 MariaDB),则没有 information_schema table,因此您无法通过任何查询获取此信息。您需要想出一种方法来解析视图定义,这是一项复杂的任务,因为它可能具有多种 SELECT 语法。

mysql> select view_definition from information_schema.views where table_name='v';
+--------------------------------------------------------------+
| VIEW_DEFINITION                                              |
+--------------------------------------------------------------+
| select `test2`.`mytable`.`id` AS `id` from `test2`.`mytable` |
+--------------------------------------------------------------+