2017-05-03 2 views
9

테이블 A는 테이블 B (id)에 대한 외래 키 제약 조건 (유형)을 갖습니다. 그러나 type은 null이 아니고 id는 null입니다.테이블간에 외래 키 제약 열 정보 찾기

외래 키 제약 조건을 살펴보고 해당 열 유형과 null 가능 열을 일치시켜 동기화 여부를 확인하는 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 열에 대한 합법적 인 이유가있을 수 있지만 관련 열의 형식/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은 조건이 요청 된 일치하지 않는 데이터 유형에 관한 것입니다. –