How to get primary key of table?

前端 未结 14 2303
不思量自难忘°
不思量自难忘° 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: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'
    

提交回复
热议问题