How to get primary key of table?

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

    SELECT kcu.column_name, kcu.ordinal_position
    FROM   information_schema.table_constraints tc
    INNER JOIN information_schema.key_column_usage kcu
    ON     tc.CONSTRAINT_CATALOG = kcu.CONSTRAINT_CATALOG
    AND    tc.CONSTRAINT_SCHEMA = kcu.CONSTRAINT_SCHEMA
    AND    tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME
    WHERE  tc.table_schema = schema()             -- only look in the current schema
    AND    tc.constraint_type = 'PRIMARY KEY'
    AND    tc.table_name = ''    -- specify your table.
    ORDER BY kcu.ordinal_position
    

提交回复
热议问题