简体   繁体   English

从多个表中获取所有列的最大值

[英]Get maximum value across all columns from multiple tables

how do i get the maximum primary key of all tables in my DB (mysql)?如何获取数据库(mysql)中所有表的最大主键?

I have following query to retrieve all columns from all tables that are primary key and is INT datatype from my_db database我有以下查询来检索all columns from all tables主键并且是my_db数据库中的INT数据类型

SELECT 
    table_name, column_name
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    table_schema = 'my_db'
        AND column_key = 'PRI'
        AND data_type LIKE '%int%'
ORDER BY TABLE_NAME , COLUMN_NAME

but now, I'm stucked at getting the maximum values from all these columns across all table.但是现在,我坚持从所有表中的所有这些列中获取最大值。 Is there a way to achieve this?有没有办法做到这一点? My expected output would be single integer number which is the largest across all these columns.我预期的 output 将是单个 integer 编号,这是所有这些列中最大的。

Thank you!谢谢!

Assuming that all the columns have a compatible type (which you are checking for), then you can construct the query using the metadata:假设所有列都具有兼容的类型(您正在检查),那么您可以使用元数据构造查询:

select group_concat(replace(replace('select max([column_name]) from [table_name]', '[column_name]', column_name), '[table_name]', table_name)
                    separator '\nunion all\n')
from INFORMATION_SCHEMA.COLUMNS
where table_schema = 'my_db' and
     column_key = 'PRI' and
     data_type LIKE '%int%'
order by TABLE_NAME, COLUMN_NAME;

I would just copy the query and run it.我只是复制查询并运行它。 But you can automate the process more by assigning the resulting string a variable and using prepare / exec .但是您可以通过为结果字符串分配一个变量并使用prepare / exec来进一步自动化该过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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