代码之家  ›  专栏  ›  技术社区  ›  sid_com

DBI:如何判断第一列是否是自动增量列?

  •  1
  • sid_com  · 技术社区  · 6 年前

    有了这些信息,是否可以可靠地判断表的第一列是否是自动递增列?

    可用信息如下:

    database handle ($dbh)
    database name
    table name
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   GMB    6 年前

    你可以查询 table COLUMNS in the mysql information schema 使用列 EXTRA .

    您将假定自动增量列的数据类型为整数,不可为空,并且没有默认值。

    my $sql = q{SELECT 1
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE 
        TABLE_SCHEMA = ?
        AND TABLE_NAME = ?
        AND ORDINAL_POSITION = 1
        AND DATA_TYPE = 'int'
        AND COLUMN_DEFAULT IS NULL
        AND IS_NULLABLE = 'NO'
        AND EXTRA like '%auto_increment%'};
    
    my ($first_col_is_autoincrement) =         
       $dbh->selectrow_array( $sql, undef, $db_name, $table_name );
    

    也可能使用 the DBI catalog functions 以独立于数据库的方式实现相同的操作。