在表上显示约束命令


224

我有尝试设置PK FK关系的表,但我想对此进行验证。如何显示PK / FK约束?我看到了手册页,但未显示示例,我的Google搜索也没有结果。我的数据库是credentialing1,我的约束表是practicescred_insurances

Answers:


414

我用

SHOW CREATE TABLE mytable;

这向您显示了以mytable当前格式接收所需的SQL语句。您可以看到所有列及其类型(如DESC),但它还显示约束信息(以及表类型,字符集等)。


8
我不认为这表明即将到来的fk关系?例如,a.col_one references b.col_one并且show create table b中将不包含有关上述关系的详细信息。
Vineet Menon 2014年

1
我确认此命令不显示外键约束。
Kemin Zhou

2
请注意,从10.2开始的MariaDB将在此处返回尴尬的结果。jira.mariadb.org/browse/MDEV-15377
stamster

117

只需查询INFORMATION_SCHEMA:

USE INFORMATION_SCHEMA;
SELECT TABLE_NAME,
       COLUMN_NAME,
       CONSTRAINT_NAME,
       REFERENCED_TABLE_NAME,
       REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "<your_database_name>" 
      AND TABLE_NAME = "<your_table_name>" 
      AND REFERENCED_COLUMN_NAME IS NOT NULL;

14
这是最佳答案,因为它以可以编程方式使用的格式为您提供结果。当然,您需要添加WHERE子句以缩小结果范围
Naveed Hasan 2014年

这帮助我找到了一个损坏的表,该表的“ id”列引用了多个外键。难怪该表收到1452 IntegrityError。
Vicky T

这是一个很好的答案!感谢@ Resh32
simhumileco '17

我喜欢您在答案前加上“简单”字样。很好的答案!
leviathanbadger

那不会显示实际的约束规则-例如ON UPDATE CASCADE
stamster

19

经过验证的答案的主要问题是您必须解析输出以获取信息。这是一个查询,使您可以更方便地获取它们:

SELECT cols.TABLE_NAME, cols.COLUMN_NAME, cols.ORDINAL_POSITION,
cols.COLUMN_DEFAULT, cols.IS_NULLABLE, cols.DATA_TYPE,
    cols.CHARACTER_MAXIMUM_LENGTH, cols.CHARACTER_OCTET_LENGTH,
    cols.NUMERIC_PRECISION, cols.NUMERIC_SCALE,
    cols.COLUMN_TYPE, cols.COLUMN_KEY, cols.EXTRA,
    cols.COLUMN_COMMENT, refs.REFERENCED_TABLE_NAME, refs.REFERENCED_COLUMN_NAME,
    cRefs.UPDATE_RULE, cRefs.DELETE_RULE,
    links.TABLE_NAME, links.COLUMN_NAME,
    cLinks.UPDATE_RULE, cLinks.DELETE_RULE
FROM INFORMATION_SCHEMA.`COLUMNS` as cols
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS refs
ON refs.TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND refs.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND refs.TABLE_NAME=cols.TABLE_NAME
    AND refs.COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cRefs
ON cRefs.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
    AND cRefs.CONSTRAINT_NAME=refs.CONSTRAINT_NAME
LEFT JOIN INFORMATION_SCHEMA.`KEY_COLUMN_USAGE` AS links
ON links.TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND links.REFERENCED_TABLE_SCHEMA=cols.TABLE_SCHEMA
    AND links.REFERENCED_TABLE_NAME=cols.TABLE_NAME
    AND links.REFERENCED_COLUMN_NAME=cols.COLUMN_NAME
LEFT JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS cLinks
ON cLinks.CONSTRAINT_SCHEMA=cols.TABLE_SCHEMA
    AND cLinks.CONSTRAINT_NAME=links.CONSTRAINT_NAME
WHERE cols.TABLE_SCHEMA=DATABASE()
    AND cols.TABLE_NAME="table"

11

afaik向您提出请求information_schema需要特权。如果您需要简单的键列表,可以使用以下命令:

SHOW INDEXES IN <tablename>

怎么称呼information_schema比这更好呢,非常感谢
Eiad Samman

6

尝试做:

SHOW TABLE STATUS FROM credentialing1;

外键约束被列在评论的输出列。


3
我在“评论”列中仅看到表格评论。这可能与InnoDB类型有关。
clockworkgeek 2012年

1
评论仅用于用户评论。可以肯定的是,这不是FK定义的存储位置!如果它们适合您-它必须已经由某些RDBMS工具代表您完成。
stamster

6

您可以使用此:

select
    table_name,column_name,referenced_table_name,referenced_column_name
from
    information_schema.key_column_usage
where
    referenced_table_name is not null
    and table_schema = 'my_database' 
    and table_name = 'my_table'

为了获得更好的格式输出,请使用以下命令:

select
    concat(table_name, '.', column_name) as 'foreign key',  
    concat(referenced_table_name, '.', referenced_column_name) as 'references'
from
    information_schema.key_column_usage
where
    referenced_table_name is not null
    and table_schema = 'my_database' 
    and table_name = 'my_table'

ORA-00942:表或视图不存在00942。00000-“表或视图不存在” *原因:*操作:第29行的错误:列:5第29行是“ information_schema.key_column_usage”
边界

2
@noboundaries,您正在Oracle上尝试,问题是关于MySQL的
ymajoros 2014年

1

类似于@ Resh32,但无需使用以下USE语句:

SELECT TABLE_NAME,
       COLUMN_NAME,
       CONSTRAINT_NAME,
       REFERENCED_TABLE_NAME,
       REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "database_name" 
      AND TABLE_NAME = "table_name" 
      AND REFERENCED_COLUMN_NAME IS NOT NULL;

有用的,例如使用ORM。


那不会显示实际的约束规则-例如ON UPDATE CASCADE
stamster

0

oracle也有一个叫做mysqlshow的工具

如果使用--k keys $table_name选项运行它,将显示密钥。

SYNOPSIS
   mysqlshow [options] [db_name [tbl_name [col_name]]]
.......
.......
.......
·   --keys, -k
   Show table indexes.

例:

╰─➤  mysqlshow -h 127.0.0.1 -u root -p --keys database tokens
Database: database  Table: tokens
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field           | Type             | Collation          | Null | Key | Default | Extra          | Privileges                      | Comment |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id              | int(10) unsigned |                    | NO   | PRI |         | auto_increment | select,insert,update,references |         |
| token           | text             | utf8mb4_unicode_ci | NO   |     |         |                | select,insert,update,references |         |
| user_id         | int(10) unsigned |                    | NO   | MUL |         |                | select,insert,update,references |         |
| expires_in      | datetime         |                    | YES  |     |         |                | select,insert,update,references |         |
| created_at      | timestamp        |                    | YES  |     |         |                | select,insert,update,references |         |
| updated_at      | timestamp        |                    | YES  |     |         |                | select,insert,update,references |         |
+-----------------+------------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table  | Non_unique | Key_name                 | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tokens | 0          | PRIMARY                  | 1            | id          | A         | 2           |          |        |      | BTREE      |         |               |
| tokens | 1          | tokens_user_id_foreign   | 1            | user_id     | A         | 2           |          |        |      | BTREE      |         |               |
+--------+------------+--------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.