简体   繁体   中英

Display information from an unknown number of tables in a Database

I would like to ask, is it possible to display columns' name, type, size etc. from several tables inside a Database using single query? The problem is that tables will never be the same so I can't just hard code them. I need to selecth the whole database. For example:

SELECT d1.*, d2.* FROM database1.table1 d1, database2.table1 d2

As you can see, I have two databases here. With the above query I've achieved to print out information about table1 from both databases. However, I'm looking for a dynamic way to print out all tables from the database at the same time. Databases and table as I said, will not always be the same. Is that possible?

Looking for an output like:

`

 |dbname|tname|fname|typename|size|isPk|isFk| 
 |------------------------------------------| 
 | db1  |tbl1 |u_id |VARCHAR | 4  |YES | NO |

` etc.

Thanks in advance.

All the information you need is exposed through MySQL's information_schema views . Almost all of it is in the "information_schema.columns" table.

select table_schema, table_name, column_name, 
       data_type, character_maximum_length, column_key
from information_schema.columns
where table_schema in ( 'db-1-name', 'db-2-name')
order by table_schema, table_name, ordinal_position

The column "character_maximum_length" only applies to variable-length columns, but it should be fairly easy to extend the query to display the lengths of integers, big integers, dates, etc.

Information about foreign key constraints is in "information_schema.key_column_usage". You just need to join that to "information_schema.columns".

select c.table_schema, c.table_name, c.column_name, 
       c.data_type, c.character_maximum_length, c.column_key,
       k.referenced_table_name
from information_schema.columns c
left join information_schema.key_column_usage k
       on c.table_catalog = k.table_catalog 
      and c.table_schema = k.table_schema
      and c.table_name = k.table_name
      and c.column_name = k.column_name
      and k.referenced_table_name is not null
where c.table_schema in ( 'db-1-name', 'db-2-name')
order by c.table_schema, c.table_name, c.ordinal_position

To select DB info you can have a look at the output of

SELECT * 
FROM information_schema.columns
WHERE table_schema in ('database1', 'database2')
AND table_name in ('table1', 'table2')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM