0

I am developing a PHP web based data entry tool with MySQL as the database. However the database will undoubtedly change whilst the data entry is going on (there is a lot of it to be done so we have started it so that it runs in parallel to the other development).

I have constructed the SQL queries so that the php can automatically:

  1. Determine what tables are in the database
  2. List tables with a certain prefix so that only ones that data entry should use are listed

However, what I cant figure out (despite checking php, sql and mysql manuals and tutorials) is how to automatically pull tables that are connected by foreign key, so that data entry have a list of items to choose from for the given table. So in short, how do I - using php - determine:

  1. Any foreign keys for the given table
  2. The table name that the foreign key points to

WITHOUT hard-coding any table names into the SQL queries?

Manse
  • 37,765
  • 10
  • 83
  • 108
  • ManseUK, thanks for the changes you made. I can see that they make my post more readable and I will remember to put lists in comment blocks in future! – Touros Spoon Mar 21 '12 at 15:22
  • http://stackoverflow.com/questions/1143728/how-can-i-find-which-tables-reference-a-given-table-in-oracle-sql-developer – zod Mar 21 '12 at 15:39

1 Answers1

0

A quick way to list your Foreign Key references using the KEY_COLUMN_USAGE view:

SELECT CONCAT( table_name, '.',
 column_name, ' -> ',
 referenced_table_name, '.',
 referenced_column_name ) AS list_of_fks
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = (your schema name here)
 AND REFERENCED_TABLE_NAME is not null
ORDER BY TABLE_NAME, COLUMN_NAME;

This query does assume that the constraints and all referenced and referencing tables are in the same schema.

For InnoDB tables, using the Comment field of SHOW TABLE STATUS is useful for extracting foreign key information for older versions of MySQL.

I am unaware of any other way than the above 2 methods.

Happy coding!

Ryan Kempt
  • 4,200
  • 6
  • 30
  • 41