Select all the table and column from a database with primary / unique and foreign key attribute

226 views Asked by At

Using MySQL 8

I need to import in LucidChart the ER extracted from a database.

The following is the query they ask to exec to get the rows with all the info they need for the import. Unfortunately, this is not working as the only keys I can see are the primary keys. I tried to understand what's wrong and why is messing up with the other keys but I can't figure it out.

 SELECT 'mysql' dbms
      , t.TABLE_SCHEMA 
      , t.TABLE_NAME 
      , c.COLUMN_NAME
      , c.ORDINAL_POSITION
      , c.DATA_TYPE
      , c.CHARACTER_MAXIMUM_LENGTH
      , n.CONSTRAINT_TYPE
      , k.REFERENCED_TABLE_SCHEMA
      , k.REFERENCED_TABLE_NAME
      , k.REFERENCED_COLUMN_NAME 
   FROM INFORMATION_SCHEMA.TABLES t 
   LEFT 
   JOIN INFORMATION_SCHEMA.COLUMNS c 
     ON t.TABLE_SCHEMA = c.TABLE_SCHEMA 
    AND t.TABLE_NAME = c.TABLE_NAME 
   LEFT 
   JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE k 
     ON c.TABLE_SCHEMA = k.TABLE_SCHEMA 
    AND c.TABLE_NAME = k.TABLE_NAME 
    AND c.COLUMN_NAME = k.COLUMN_NAME 
   LEFT 
   JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS n 
     ON k.CONSTRAINT_SCHEMA = n.CONSTRAINT_SCHEMA 
    AND k.CONSTRAINT_NAME = n.CONSTRAINT_NAME 
    AND k.TABLE_SCHEMA = n.TABLE_SCHEMA 
    AND k.TABLE_NAME = n.TABLE_NAME 
  WHERE t.TABLE_TYPE = 'BASE TABLE' 
    AND t.TABLE_SCHEMA NOT IN('INFORMATION_SCHEMA','mysql','performance_schema');

The key info is that I'm using Laravel migrations. I think I already found the answer but I'll leave it open.

0

There are 0 answers