2017-05-03 65 views
9

表A对表B(id)具有外键约束(类型)。但是,类型不为null,id可以为空。查找表之间的外键约束列信息

我想使用information_schema来构建一个查询,它将查看外键约束并匹配列类型和可空列来查看它们是否同步,但是我遇到了逻辑问题。

select kcu.table_name, kcu.column_name, c.column_type, c.is_nullable,kcu.referenced_table_name, kcu.referenced_column_name,c.column_type, c.is_nullable 
from key_column_usage kcu 
inner join columns c on c.table_schema=kcu.table_schema and c.column_name=kcu.column_name and c.table_name=kcu.table_name 
where kcu.referenced_table_name='Table_B' and kcu.table_name='Table_A'; 

我知道这个语法是不正确的 - 这只是我迄今为止能够放在一起的所有东西。我希望能够为数据库中的每个表执行此操作,并通过table_name和column_name对其进行排序。它可以排除column_type和is_nullable字段相同的列。

回答

5

在外部约束的一边有NULLABLE列可能是合法的原因,但是这会比较所涉及列的类型/可空属性。

SELECT 
     kcu.constraint_schema 
    , kcu.constraint_name 
    , kcu.referenced_table_name 
    , kcu.referenced_column_name 
    , kcu.table_name 
    , kcu.column_name 
    , refcol.column_type referenced_column_type 
    , childcol.column_type 
    , refcol.is_nullable referenced_is_nullable 
    , childcol.is_nullable 

FROM information_schema.key_column_usage kcu 
INNER JOIN information_schema.columns refcol 
     ON refcol.table_schema = kcu.referenced_table_schema 
     AND refcol.table_name = kcu.referenced_table_name 
     AND refcol.column_name = kcu.referenced_column_name 
INNER JOIN information_schema.columns childcol 
     ON childcol.table_schema = kcu.table_schema 
     AND childcol.table_name = kcu.table_name 
     AND childcol.column_name = kcu.column_name 

WHERE (
     refcol.is_nullable <> childcol.is_nullable 
     OR 
     refcol.column_type <> childcol.column_type 
    ) 
AND kcu.TABLE_SCHEMA = 'rextester' #change this value to suit 
ORDER BY 
     kcu.table_name 
    , kcu.column_name 
; 

See a working example (click the run button)

+0

'refcol.column_type <> childcol.column_type' - 我认为这应该是不可能的。 –

+0

@Paul Spiegel关于请求条件不匹配的数据类型。 –