简体   繁体   English

如何获得MYSQL数据库中表和视图的from子句中使用的所有表和视图的列表?

[英]How can I get a list of all tables and views used in the from clause of tables and views in a MYSQL Database?

I'm trying to determine what tables and views are used for all tables and views in a MYSQL database. 我正在尝试确定哪些表和视图用于MYSQL数据库中的所有表和视图。 For example I need to see that: 例如,我需要看到:

table A uses view B
table A also uses table C   
table C uses table D
table C also uses view X

I know I have to do a query against the information_schema and join it against another query of the information_schema, but don't know what those queries should be. 我知道我必须对information_schema进行查询,并针对information_schema的另一个查询将其加入,但是不知道这些查询应该是什么。

Any help is appreciated. 任何帮助表示赞赏。

To get a list of the tables and views used in the FROM clause of views for a given database you could use: 要获取给定数据库的视图的FROM子句中使用的表和视图的列表,可以使用:

SELECT CONCAT('`', v.table_schema,'`.`', v.table_name,'`') AS 'view', 
GROUP_CONCAT(CONCAT(' `', t.table_schema,'`.`', t.table_name, '`')) AS 'tables' 
FROM information_schema.tables t
JOIN information_schema.views v
  ON (v.view_definition REGEXP CONCAT('`', t.table_schema, '`.`' , t.table_name, '`') = 1)
WHERE v.table_schema = 'sakila'
GROUP BY 1;

MySQL rather helpfully expands the table names used when storing the view definition to include the schema name as well and then escapes the lot with backticks. MySQL相当有用地扩展了在存储视图定义时使用的表名,使其也包括架构名,然后使用反引号进行转义。 By matching against this full string rather than just the table name we can eliminate matches against partial strings, column names and aliases that happen to match as well. 通过匹配这个完整的字符串而不只是表名,我们可以消除与部分字符串,列名和别名碰巧匹配的匹配。

I'm assume that when you say "table C uses table D" in your question you are referring to a foreign key relationship between the two. 我假设当您在问题中说“表C使用表D”时,您指的是两者之间的外键关系。 You can get this data from information_schema.key_column_usage . 您可以从information_schema.key_column_usage获取此数据。

eg 例如

SELECT CONCAT('`', table_schema, '`.`', table_name, '`') AS 'table', 
GROUP_CONCAT(DISTINCT CONCAT(' `', referenced_table_schema, '`.`', referenced_table_name, '`')) AS 'referenced table(s)' 
FROM information_schema.key_column_usage 
WHERE 1 = 1
AND table_schema = 'sakila'
AND referenced_column_name IS NOT NULL
GROUP BY 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM