尝试将列连接到 key_column_usage

Trying to join columns to key_column_usage

我正在尝试获取以下信息,但我的连接语法有问题:

我需要以下内容:

我有这个,但它不起作用(我知道语法不正确——但这是我的起点)

select kcu.table_schema, kcu.table_name, kcu.column_name, c.column_type, kcu.referenced_table_schema, kcu.referenced_table_name, kcu.referenced_column_name, c.column_type
from key_column_usage kcu
inner join columns c on kcu.table_schema=c.table_schema and kcu.table_name=c.table_name and kcu.column_name=c.column_name
where kcu.referenced_table_name='table_to_check' and kcu.referenced_column_name='column_to_check';

您的查询在语法上是正确的,但是您缺少对 columns table 的附加 JOIN 以获得 kcu.referenced_column_namecolumn_type - 您的版本加入一次并显示引用 column_type 两次。

第二个 JOIN 应该在 referenced_table_schemareferenced_table_namereferenced_column_name 列上。

例如

SELECT kcu.table_schema, kcu.table_name, kcu.column_name, c1.column_type, 
       kcu.referenced_table_schema, kcu.referenced_table_name, 
       kcu.referenced_column_name, c2.column_type
  FROM information_schema.key_column_usage kcu 
  JOIN information_schema.columns c1 
    ON c1.table_schema = kcu.table_schema AND 
       c1.table_name   = kcu.table_name AND 
       c1.column_name  = kcu.column_name
  JOIN information_schema.columns c2 
    ON c2.table_schema = kcu.referenced_table_schema AND 
       c2.table_name   = kcu.referenced_table_name AND 
       c2.column_name  = kcu.referenced_column_name
 WHERE kcu.referenced_table_schema = 'schema_to_check' 
   AND kcu.referenced_table_name   = 'table_to_check' 
   AND kcu.referenced_column_name  = 'column_to_check';