46

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user3148861
  • 461
  • 1
  • 4
  • 3
  • 1
    use mysql workbench to reverse engineer DB and give you an ER diagram with all relationships – Satya Dec 31 '13 at 09:34
  • 2
    Except for foreign key constraints, there's nothing in the database that encodes relations. If the programmers haven't provided documentation, it's just in their heads and you need to figure it out empirically. That's why they pay you the big bucks. – Barmar Dec 31 '13 at 09:37
  • 1
    Possible a duplicate of [this](http://stackoverflow.com/questions/201621/how-do-i-see-all-foreign-keys-to-a-table-or-column). You can extract foreign keys this way. – Amir Pashazadeh Dec 31 '13 at 09:37
  • Hi Satya, can you provide more details? reverse engineer DB is what? – user3148861 Dec 31 '13 at 10:03
  • **Pro tips, just ask your senior who know it.** Often it is a mess left by previous people. You only need to know few of those. And probably nobody in company know all Tables also. Ask the documentation or diagram for it, they probably don't have it also. – A. Go Dec 14 '20 at 03:21

9 Answers9

63

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

xudre
  • 2,731
  • 2
  • 19
  • 19
25

Try this:

select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS;
BaBL86
  • 2,602
  • 1
  • 14
  • 13
13

Try

SELECT
`TABLE_NAME`,
`COLUMN_NAME`,
`REFERENCED_TABLE_NAME`,
`REFERENCED_COLUMN_NAME`
FROM `information_schema`.`KEY_COLUMN_USAGE`
WHERE `CONSTRAINT_SCHEMA` = 'YOUR_DATABASE_NAME' AND
`REFERENCED_TABLE_SCHEMA` IS NOT NULL AND
`REFERENCED_TABLE_NAME` IS NOT NULL AND
`REFERENCED_COLUMN_NAME` IS NOT NULL

do not forget to replace YOUR_DATABASE_NAME with your database name!

Mostafa Lavaei
  • 1,960
  • 1
  • 18
  • 27
12

A quick method of visualizing relationships in MySQL is reverse engineering the database with MySQL Workbench.

This can be done using the reverse engineering too, which will result in an entity-relationship diagram much like the following (though you may have to organize it yourself, once it is generated):

ERD

Sculper
  • 756
  • 2
  • 12
  • 24
Fanta Sylla
  • 129
  • 1
  • 2
  • 7
    Not if you are dealing with a legacy code with more than 500 tables! – hpaknia Jan 17 '17 at 19:06
  • 1
    This is cool! Can the relationship also be automatically generated? I only the standalone tables, wonder if that is possible. – skyuuka Mar 31 '21 at 20:06
5

SELECT 
    count(1) totalrelationships ,
    c.table_name tablename,
    CONCAT(' ',GROUP_CONCAT(c.column_name ORDER BY ordinal_position SEPARATOR ', ')) columnname,
    CONCAT(' ',GROUP_CONCAT(c.column_type ORDER BY ordinal_position SEPARATOR ', ')) columntype    
FROM
    information_schema.columns c RIGHT JOIN
    (SELECT column_name , column_type FROM information_schema.columns WHERE 
    -- column_key in ('PRI','MUL') AND  -- uncomment this line if you want to see relations only with indexes
    table_schema = DATABASE() AND table_name = 'YourTableName') AS p
    USING (column_name,column_type)
WHERE
    c.table_schema = DATABASE()
    -- AND c.table_name != 'YourTableName'
    GROUP BY tablename
    -- HAVING (locate(' YourColumnName',columnname) > 0) -- uncomment this line to search for specific column 
    ORDER BY totalrelationships desc, columnname
;
  • This probably is the better answer out there. You generally want to know relationship of a single table or a single column of a table. Read between the lines before you copy-paste it to your sql terminal. – bmlkc Jun 09 '19 at 14:13
5

Based on xudre's answer, you can execute the following to see all the relations of a schema:

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`
WHERE `TABLE_SCHEMA` = 'YourSchema'
AND   `REFERENCED_TABLE_NAME` IS NOT NULL  -- Only tables with foreign keys

What I want in most cases is to know all FKs that point to a specific table. In this case I run:

SELECT 
  `TABLE_SCHEMA`,                          -- Foreign key schema
  `TABLE_NAME`,                            -- Foreign key table
  `COLUMN_NAME`                            -- Foreign key column
FROM `INFORMATION_SCHEMA`.`KEY_COLUMN_USAGE`  
WHERE `TABLE_SCHEMA` = 'YourSchema'
AND   `REFERENCED_TABLE_NAME` = 'YourTableName'
Lucas Basquerotto
  • 7,260
  • 2
  • 47
  • 61
4

1) Go into your database:
use DATABASE;

2) Show all the tables:
show tables;

3) Look at each column of the table to gather what it does and what it's made of:
describe TABLENAME;

4) Describe is nice since you can figure out exactly what your table columns do, but if you would like an even closer look at the data itself: select * from TABLENAME
If you have big tables, then each row usually has an id, in which case I like to do this to just get a few lines of data and not have the terminal overwhelmed:
select * from TABLENAME where id<5 - You can put any condition here you like.

This method give you more information than just doing select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS;, and it also provides you with more bite-sized information each time.

EDIT

As the comments suggested, the above WHERE id < 5 was a bad choice as a conditional placeholder. It is not a good idea to limit by ID number, especially since the id is usually not trustworthy to be sequential. Add LIMIT 5 at the end of the query instead.

Roman
  • 8,826
  • 10
  • 63
  • 103
  • using WHERE id<5 is troublesome when you don't know the ID, and no one can be sure that those IDs are still valid. You should use LIMIT 5 to limit the number of records. – Salketer Dec 23 '16 at 10:18
  • @Salketer You are right. It was a poor choice of `WHERE` clause – Roman Jan 03 '17 at 07:18
  • select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS; works – PHPFan Mar 14 '18 at 11:56
0

One option is : You can do reverse engineering to understand it in diagrammatic way.

When you install MySQL, you will get MySQLWorkbench. You need to open it and choose the database you want to reverse engineer. Click on Reverse Engineer option somewhere you find under the tools or Database menu. It will ask you to choose the tables. Either you select the tables you want to understand or choose the entire DB. It will generate a diagram with relationships.

-1

you can use:

SHOW CREATE TABLE table_name;
Arnab Nandy
  • 6,472
  • 5
  • 44
  • 50
balderys
  • 47
  • 1