SQL查询查找表的主键?

时间:2012-09-11 23:16:57

标签: mysql sql sql-server oracle

如何使用查询找到哪个列是表的主键

9 个答案:

答案 0 :(得分:21)

这是重复的question

对Lukmdo的回答是:

可能不建议但工作得很好:

show index from TABLE where Key_name = 'PRIMARY' ;

可靠的方法是使用information_schema:

SELECT k.COLUMN_NAME
FROM information_schema.table_constraints t
LEFT JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
    AND t.table_schema=DATABASE()
    AND t.table_name='owalog';

答案 1 :(得分:12)

对于Oracle,您可以在ALL_CONSTRAINTS表中查找:

SELECT a.COLUMN_NAME
FROM all_cons_columns a INNER JOIN all_constraints c 
     ON a.constraint_name = c.constraint_name 
WHERE c.table_name = 'TBL'
  AND c.constraint_type = 'P';

<强> DEMO

对于SQL Server,已经回答here,对于MySQL,请检查@ajon's answer

答案 2 :(得分:9)

对于MySQL:

SELECT GROUP_CONCAT(COLUMN_NAME), TABLE_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  TABLE_SCHEMA = '**database name**'
  AND CONSTRAINT_NAME='PRIMARY'
GROUP BY TABLE_NAME;

警告包含两列的主键会将它们分隔为逗号(,

答案 3 :(得分:5)

在SQL server中尝试此查询:

SELECT     X.NAME AS INDEXNAME,
           COL_NAME(IC.OBJECT_ID,IC.COLUMN_ID) AS COLUMNNAME
FROM       SYS.INDEXES  X 
INNER JOIN SYS.INDEX_COLUMNS  IC 
        ON X.OBJECT_ID = IC.OBJECT_ID
       AND X.INDEX_ID = IC.INDEX_ID
WHERE      X.IS_PRIMARY_KEY = 1
  AND      OBJECT_NAME(IC.OBJECT_ID)='YOUR_TABLE'

答案 4 :(得分:3)

以下查询提供给定数据库中所有主键的列表。

SELECT DISTINCT TABLE_NAME ,column_name
    FROM INFORMATION_SCHEMA.key_column_usage
    WHERE TABLE_SCHEMA IN ('*your_db_name*');

答案 5 :(得分:2)

在MySQL中

SHOW COLUMNS FROM `table_name`;

这显示了列的详细信息,即字段,数据类型,键等。

答案 6 :(得分:0)

向左加入table_constraints似乎需要更多时间。 我使用Information_schema.COLUMNS

SELECT TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME FROM Information_schema.Columns 在哪里COLUMN_KEY =“ PRI”和TABLE_SCHEMA = DATABASE()

答案 7 :(得分:0)

更简单的方法:

DESC TABLE;

它向您展示了 TABLE 的结构;

答案 8 :(得分:-1)

对于MSSQL: SELECT DISTINCT C.TABLE_NAME,C.COLUMN_NAME,C.DATA_TYPE 从sys.indexes我 INNER JOIN sys.index_columns I.OBJECT_ID = IC.OBJECT_ID和I.INDEX_ID = IC.INDEX_ID上的IC 内联接information_schema.columns C ON COL_NAME(IC.OBJECT_ID,IC.COLUMN_ID)= C.COLUMN_NAME I.IS_PRIMARY_KEY = 1