Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to find where a specific primary key is used as a foreign key in other tables?

I'm working on implementing a function to prevent removal of certain elements in a database (through the front end) if they have other items associated with them in other tables. Otherwise those other tables are looking for keys that aren't there.

If you understood that my hat is off to you.

I have many sets of tables to look through and need either a SQL query or a MySQL Workbench feature that can tell me, on entry of the primary key (column name, not actual value), if that key is used as a foreign key somewhere else.

Otherwise if anyone knows an offhand workaround, that would be great too!

like image 255
spuriosity Avatar asked Oct 06 '11 09:10

spuriosity


People also ask

How do I find the foreign key references for a table in mysql?

To see foreign key relationships of a table: SELECT TABLE_NAME, COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA. KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'db_name' AND REFERENCED_TABLE_NAME = 'table_name';

Can a primary key be a foreign key in the same table mysql?

If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied.

How can we find primary key and foreign key relationship in SQL?

If we want to know the table's primary keys and foreign keys. We can simply use an “information_schema. key_column_usage” view, this view will return all of the table's foreign keys and primary keys.


1 Answers

SELECT 
  table_name, column_name     
FROM
  information_schema.key_column_usage
WHERE
  referenced_table_name = '<table>'
  and referenced_column_name = '<primary key column>'
like image 200
StevieG Avatar answered Oct 13 '22 22:10

StevieG