Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all the relations between all mysql tables?

How to find all the relations between all MySQL tables? If for example, I want to know the relation of tables in a database of having around 100 tables.

Is there anyway to know this?

like image 964
user3148861 Avatar asked Dec 31 '13 09:12

user3148861


People also ask

How can I see the relationship between tables 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';

Where do you check the relations between the tables?

To view your table relationships, click Relationships on the Database Tools tab. The Relationships window opens and displays any existing relationships. If no table relationships have been defined and you are opening the Relationships window for the first time, Access prompts you to add a table or query to the window.

How do I see relations between tables in mysql workbench?

(To view all the relationships in the sakila database, see Figure 9.35, “The sakila Database EER Diagram”.) Click the Properties tab of the panel on the lower left and then click one of the tables on the canvas. This action displays the properties of the table in the Properties window, as the next figure shows.


2 Answers

The better way, programmatically speaking, is gathering data from INFORMATION_SCHEMA.KEY_COLUMN_USAGE table as follows:

SELECT    `TABLE_SCHEMA`,                          -- Foreign key schema   `TABLE_NAME`,                            -- Foreign key table   `COLUMN_NAME`,                           -- Foreign key column   `REFERENCED_TABLE_SCHEMA`,               -- Origin key schema   `REFERENCED_TABLE_NAME`,                 -- Origin key table   `REFERENCED_COLUMN_NAME`                 -- Origin key column FROM   `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE`  -- Will fail if user don't have privilege WHERE   `TABLE_SCHEMA` = SCHEMA()                -- Detect current schema in USE    AND `REFERENCED_TABLE_NAME` IS NOT NULL; -- Only tables with foreign keys 

There are more columns info like ORDINAL_POSITION that could be useful depending your purpose.

More info: http://dev.mysql.com/doc/refman/5.1/en/key-column-usage-table.html

like image 106
xudre Avatar answered Oct 10 '22 01:10

xudre


Try this:

select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS; 
like image 35
BaBL86 Avatar answered Oct 10 '22 01:10

BaBL86