如何查找没有自动增量的所有主键

时间:2013-03-19 13:48:55

标签: mysql

如何查找数据库中所有表中的所有主键,这些表中没有自动增量标识符。我们有大量的表格,并且想要识别所有在主键上没有自动增量标识符的表格。

2 个答案:

答案 0 :(得分:6)

您可以从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')

这将查找具有auto_increment列的一个数据库中的所有表,然后返回其余表。这也正确地检测了具有复合键的表。

答案 1 :(得分: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”。

相关问题