How to get primary key of table?

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

    A better way is to use SHOW KEYS since you don't always have access to information_schema. The following works:

    SHOW KEYS FROM table WHERE Key_name = 'PRIMARY'
    

    Column_name will contain the name of the primary key.

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

    Here is the Primary key Column Name

    SELECT k.column_name
    FROM information_schema.table_constraints t
    JOIN information_schema.key_column_usage k
    USING(constraint_name,table_schema,table_name)
    WHERE t.constraint_type='PRIMARY KEY'
      AND t.table_schema='YourDatabase'
      AND t.table_name='YourTable';
    
    0 讨论(0)
  • 2020-12-02 15:30

    You should use PRIMARY from key_column_usage.constraint_name = "PRIMARY"

    sample query,

    SELECT k.column_name as PK, concat(tbl.TABLE_SCHEMA, '.`', tbl.TABLE_NAME, '`') as TABLE_NAME
    FROM information_schema.TABLES tbl
    JOIN information_schema.key_column_usage k on k.table_name = tbl.table_name
    WHERE k.constraint_name='PRIMARY'
      AND tbl.table_schema='MYDB'
      AND tbl.table_type="BASE TABLE";
    
    0 讨论(0)
  • 2020-12-02 15:32

    I use SHOW INDEX FROM table ; it gives me alot of informations ; if the key is unique, its sequenece in the index, the collation, sub part, if null, its type and comment if exists, see screenshot herehere

    0 讨论(0)
  • 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 = '<your-table-name>'    -- specify your table.
    ORDER BY kcu.ordinal_position
    
    0 讨论(0)
  • 2020-12-02 15:37

    How about this:

    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = 'Your Database'
      AND TABLE_NAME = 'Your Table name'
      AND COLUMN_KEY = 'PRI';
    
    
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = 'Your Database'
      AND TABLE_NAME = 'Your Table name'
      AND COLUMN_KEY = 'UNI';
    
    0 讨论(0)
提交回复
热议问题