Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find foreign keys while scripting MySQL Workbench

I have created a DB Model and EER diagram in MySQL Workbench. I am using the workbench scripting feature to write a script to generate code to use the database after it is exported and created on a MySQL server.

As I loop over the tables, is there any way I can find foreign keys that link to the current table?

There is a 'foreignKeys' attribute on the table object, but it contains only the foreign keys pointing AWAY from the table, not those pointing to it. I want to know what other tables have foreign keys that link to the primary key of the current table (ideally without looping over every column in every other table in the model).

like image 411
Scott Saunders Avatar asked Nov 08 '25 10:11

Scott Saunders


1 Answers

You can use below query to retrieve all the constraint/foreign key in DB..

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = 'database_name';

to be more specific to your question, you can use below query..

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = 'database_name' AND
  REFERENCED_TABLE_NAME = 'table_name';
like image 150
Sh4m Avatar answered Nov 12 '25 15:11

Sh4m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!