2013-03-19 1 views
2

데이터베이스에서 자동 증분 식별자가없는 모든 테이블의 모든 기본 키를 찾는 방법. 우리는 많은 양의 테이블을 가지고 있으며 기본 키에 자동 증가 식별자가없는 모든 테이블을 식별하려고합니다.자동 증가가없는 모든 기본 키를 찾는 방법

답변

5

당신은 auto_increment 열을 가진 하나의 데이터베이스에이 모든 테이블을 찾습니다 information_schema.columns

select distinct table_name 
from information_schema.columns 
where table_schema = 'DATABASENAME' 
     and table_name not in (select table_name 
          from information_schema.columns 
          where table_schema = 'DATABASENAME' 
            and column_key = 'PRI' 
            and data_type = 'int' 
            and extra = 'auto_increment') 

에서이 정보를 추출하고 나머지 테이블을 반환 할 수 있습니다. 이것은 또한 복합 키가있는 테이블을 올바르게 감지합니다.

+1

문자 데이터 인 PK 열을 나열하고 싶지 않으므로'data_type = 'int'도 추가합니다. –

1

테이블 information_schema.columns에서 정보를 찾을 수 있습니다. column_key 열은 PRI이고 열 extra은 자동 증가 될 경우 auto_increment을 포함합니다.

SELECT 
    table_schema, 
    table_name, 
    column_name 
FROM 
    information_schema.columns 
WHERE 
    column_key = 'PRI' 
    AND extra <> 'auto_increment' 
    AND data_type = 'int' 

this SQL Fiddle에서는 샘플 테이블이 "PRI"및 각각의 컬럼에서 "AUTO_INCREMENT"을 가지고 있다고 볼 수 있습니다.

관련 문제