mysql – 查找列名与给定模式匹配的表
作者:互联网
这可能听起来有点不太现实,但我最近不得不研究远程维护的系统的数据库结构,当我想找到链接到给定表的所有列时,我发现有一些情况. (参见,原始开发人员没有创建显式关系,而是在列名中编码关系!).
例如,假设所有引用列parent.parent的列都具有表单table.somefield_parent作为记录两个字段之间关系的方法,我如何使用标准SQL命令找到所有这些关系(以及涉及的表) /内置功能?
任何MySQL或PostgreSQL的解决方案都是受欢迎的.
注意 :
>我不是在寻找数据中的模式,而是在元数据中.
>我知道我可以转储db结构并在那里搜索结果,但是我不想离开db-shell来找到这些关系(假设我正在使用psql,并且不想退出)
解决方法:
在PostgreSQL中,您可以查询系统目录表.
您还可以查询information_schema,它包含提供标准SQL显示信息方式的视图.但是,查询系统目录通常要快得多.
要查找一个特定父列的子项:
SELECT n.nspname AS schema_name
, c.relname AS table_name
, a.attname AS column_name
FROM pg_catalog.pg_attribute a
JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE a.attname ~~ E'%\\_parent'
AND NOT a.attisdropped
AND c.relkind = 'r'
AND nspname !~~ E'pg\\_%';
要根据描述找到所有相关列:
SELECT n.nspname AS parrent_schema
, c.relname AS parrent_table
, a.attname AS parrent_column
, n1.nspname AS child_schema
, c1.relname AS child_table
, a1.attname AS child_column
FROM pg_catalog.pg_attribute a
JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
JOIN pg_catalog.pg_attribute a1 ON a.attname = substring(a1.attname, '_(.*?)$')
JOIN pg_catalog.pg_class c1 ON c1.oid = a1.attrelid
JOIN pg_catalog.pg_namespace n1 ON n1.oid = c1.relnamespace
WHERE c.relkind = 'r'
AND c1.relkind = 'r'
AND n.nspname !~~ E'pg\\_%'
AND n1.nspname !~~ E'pg\\_%'
AND NOT a.attisdropped
AND NOT a1.attisdropped
-- AND n.nspname = 'public' -- to narrow it down to a specific schema
-- AND n1.nspname = 'public' -- to narrow it down to a specific schema
ORDER BY 1,2,3,4,5,6
这假设parrent列的名称中没有_.
关键元素是连接条件:
a.attname = substring(a1.attname, '_(.*?)$')
标签:sql,mysql,postgresql,relational-database,introspection 来源: https://codeday.me/bug/20190726/1540351.html