我有桌子,我已经尝试设置PK FK关系,但我想验证这一点.如何显示PK/FK限制?我看到了这个手册页,但它没有显示示例,我的谷歌搜索也没有结果.我的数据库是credentialing1
和我的约束表是practices
和cred_insurances
.
我用
SHOW CREATE TABLE mytable;
这将显示以mytable
当前形式重新标记所需的SQL语句.您可以查看所有列及其类型(如DESC
),但它还会显示约束信息(以及表类型,字符集等).
只需查询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 = "" AND TABLE_NAME = " " AND REFERENCED_COLUMN_NAME IS NOT NULL;
验证答案的主要问题是您必须解析输出以获取信息.这是一个允许您以更有用的方式获取它们的查询:
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"
afaik向您提出要求information_schema
需要特权.如果需要简单的键列表,可以使用以下命令:
SHOW INDEXES IN
尝试做:
SHOW TABLE STATUS FROM credentialing1;
外键约束列在输出的" 注释"列中.
你可以用这个:
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'