how do i get the maximum primary key of all tables in my DB (mysql)?
I have following query to retrieve all columns from all tables
that are primary key and is INT datatype from my_db
database
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.
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
.
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.