How can I get the foreign keys of a table in mysql

五迷三道 提交于 2019-11-30 15:32:11

Simple way to get foreign keys for given table:

SELECT
    `column_name`, 
    `referenced_table_schema` AS foreign_db, 
    `referenced_table_name` AS foreign_table, 
    `referenced_column_name`  AS foreign_column 
FROM
    `information_schema`.`KEY_COLUMN_USAGE`
WHERE
    `constraint_schema` = SCHEMA()
AND
    `table_name` = 'your-table-name-here'
AND
    `referenced_column_name` IS NOT NULL
ORDER BY
    `column_name`;

The INFORMATION_SCHEMA database contains details of the full schema of all other databases, including constraints:

http://dev.mysql.com/doc/refman/5.0/en/information-schema.html

You can also run a SHOW CREATE TABLE query to get the SQL to create a table, including its constraints.

Much can be retrieved from MySQL's information_schema, foreign keys included, as pointed out by dev-null-dweller.

1

SELECT * FROM information_schema.table_constraints 
         WHERE table_schema = 'dbname' AND table_name='mytable';

Instead of dbname use the function SCHEMA() to set the name of the database in USE.


2

As pointed out by Dan Grossman, the command

SHOW CREATE TABLE `yourtablename`

can be used basically get an SQL dump of the create table statement.


~3

MySQL provides a SHOW KEYS command. As such you could theoretically get the FK if you know a lower cardinality threshold and have few other keys in the table.

SHOW KEYS FROM `address` WHERE Non_unique AND CARDINALITY > 10000

As the key's cardinality changes each time the internal database is changed, this is rather theoretical. See the cardinality change for instance with running ANALYZE TABLE.


~4

It is useful to stick to a naming schema, such as foreigntablename_foreignfieldname. For example the field user_id in a table billing. Several ORMs of big Web Content Frameworks use this schema.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!