Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am creating a class which, takes a table from a database, and displays it to a web-page, with as much functionality as possible. One of the things I would like to support, would be having the class detect which columns in the table have a foreign key constraint on them, so that it can then go to those tables, get all of their values and use them in a select-box which is called when you edit those fields, to avoid someone violating foreign key constraints,

The main problem is discovering which fields have a foreign key constraint on them, and which tables they are pointing to. Does anyone know how to do this???

Thanks,

Lemiant

like image 625
lemiant Avatar asked Nov 11 '10 22:11

lemiant


People also ask

How do I find a foreign key in a table?

Open the Table Designer for the table containing the foreign key you want to view, right-click in the Table Designer, and choose Relationships from the shortcut menu. In the Foreign Key Relationships dialog box, select the relationship with properties you want to view.

How do I find the foreign key of a table in MySQL workbench?

option. In Table Editor go to Foreign Keys tab (at the bottom). Keys are displayed in the left pane and details of selected keys are displayed on the right. You can see pair of foreign and primiary columns in Column and Referenced Column columnsin the grid in the middle of the window.

Does MySQL have foreign keys?

MySQL supports foreign keys, which permit cross-referencing related data across tables, and foreign key constraints, which help keep the related data consistent.


1 Answers

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`;
like image 122
dev-null-dweller Avatar answered Sep 25 '22 15:09

dev-null-dweller