如何使用查询找到表的主键是哪一列?
9 回答
这是一个重复的问题:
这个答案归功于 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';
对于 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';
演示。
对于 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;
警告具有两列的主键将用逗号 ( ,
)分隔
在 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'
以下查询给出了给定数据库中所有主键的列表。
SELECT DISTINCT TABLE_NAME ,column_name
FROM INFORMATION_SCHEMA.key_column_usage
WHERE TABLE_SCHEMA IN ('*your_db_name*');
在我的 SQL
SHOW COLUMNS FROM `table_name`;
这显示了列的详细信息,即字段、数据类型、键等。
这是更简单的方法:
DESC TABLE;
它向您展示了 TABLE 的结构;
LEFT 加入 table_constraints 似乎需要更多时间。我使用 Information_schema.COLUMNS
SELECT TABLE_SCHEMA , TABLE_NAME , COLUMN_NAME 从 Information_schema.Columns WHERE COLUMN_KEY = "PRI" AND TABLE_SCHEMA = DATABASE()
对于 MSSQL: SELECT DISTINCT C.TABLE_NAME,C.COLUMN_NAME,C.DATA_TYPE FROM sys.indexes I INNER JOIN sys.index_columns IC ON I.OBJECT_ID = IC.OBJECT_ID AND I.INDEX_ID = IC.INDEX_ID INNER JOIN information_schema.columns C ON COL_NAME(IC.OBJECT_ID,IC.COLUMN_ID) = C.COLUMN_NAME 其中 I.IS_PRIMARY_KEY = 1