How to get primary key of table?

前端 未结 14 2115
不思量自难忘°
不思量自难忘° 2020-12-02 15:01

Is there a way to get the name of primary key field from mysql-database? For example:

I have a table like this:

+----+------+
| id | name |
+----+---         


        
相关标签:
14条回答
  • 2020-12-02 15:37

    For a PHP approach, you can use mysql_field_flags

    $q = mysql_query('select * from table limit 1');
    
    for($i = 0; $i < mysql_num_fields(); $i++)
        if(strpos(mysql_field_tags($q, $i), 'primary_key') !== false)
            echo mysql_field_name($q, $i)." is a primary key\n";
    
    0 讨论(0)
  • 2020-12-02 15:42

    Shortest possible code seems to be something like

    // $dblink contain database login details 
    // $tblName the current table name 
    $r = mysqli_fetch_assoc(mysqli_query($dblink, "SHOW KEYS FROM $tblName WHERE Key_name = 'PRIMARY'")); 
    $iColName = $r['Column_name']; 
    
    0 讨论(0)
  • 2020-12-02 15:46
    SELECT k.column_name
    FROM information_schema.key_column_usage k   
    WHERE k.table_name = 'YOUR TABLE NAME' AND k.constraint_name LIKE 'pk%'
    

    I would recommend you to watch all the fields

    0 讨论(0)
  • 2020-12-02 15:50

    use:

    show columns from tablename where `Key` = "PRI";
    
    0 讨论(0)
  • 2020-12-02 15:50

    If you want to generate the list of primary keys dynamically via PHP in one go without having to run through each table you can use

    SELECT TABLE_NAME, COLUMN_NAME
    FROM INFORMATION_SCHEMA.key_column_usage 
    WHERE table_schema = '$database_name' AND CONSTRAINT_NAME = 'PRIMARY' 
    

    though you do need to have access to the information.schema to do this.

    0 讨论(0)
  • 2020-12-02 15:51

    MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table. For eg. - the following query will show all the indexes for the products table:-

    SHOW INDEXES FROM products \G
    

    It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -

    *************************** 1. row ***************************
            Table: products
       Non_unique: 0
         Key_name: PRIMARY
     Seq_in_index: 1
      Column_name: product_id
        Collation: A
      Cardinality: 0
         Sub_part: NULL
           Packed: NULL
             Null: 
       Index_type: BTREE
          Comment: 
    Index_comment: 
    

    To just display primary key from the table use :-

    SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'
    
    0 讨论(0)
提交回复
热议问题