简体   繁体   English

一次检索数据库中所有表的 MAX 个主键值

[英]Retrieve MAX Primary Key values of all tables in a database at once

What I need to do is retrieve the maximum primary key of all tables in my database at once ?我需要做的是检索所有的表在我的数据库一次最大的主键? That is, my result will be like if I executed the below 2 queries:也就是说,如果我执行以下 2 个查询,我的结果将如下所示:

SHOW TABLES FROM DATABASE_NAME

SELECT MAX(PRIMARY_KEY) AS maxId FROM TABLE

That is那是

(first column = TableName , second column = MAX(PK) Of that table)

Pardon if I am doing something wrong.如果我做错了什么,请原谅。 I just do not want to write 80 queries because my database has 80 tables.我只是不想写 80 个查询,因为我的数据库有 80 个表。

If (and only if) your primary keys are AUTO INCREMENT variables you can do this:如果(且仅当)您的主键是AUTO INCREMENT变量,您可以这样做:

SELECT TABLE_NAME, AUTO_INCREMENT
FROM   information_schema.TABLES
WHERE  TABLE_SCHEMA = 'mydb'

Please pay attention to the situation below when choosing the method of retrieving that info and what you are going to do with it:在选择检索该信息的方法以及您打算用它做什么时,请注意以下情况:

AUTO_INCREMENT value is stored in memory, so after a server restart, AUTO_INCREMENT value is reset to: AUTO_INCREMENT 值存储在内存中,因此在服务器重启后,AUTO_INCREMENT 值重置为:

SELECT MAX(ai_col) FROM table_name FOR UPDATE;

This can break things if the database has missing FKs and, for example, you delete some rows that refer to other tables.如果数据库缺少 FK,这可能会破坏事情,例如,您删除了一些引用其他表的行。 You would end up by reusing the same id.你最终会重复使用相同的 id。

Refer to: https://dev.mysql.com/doc/refman/5.7/en/innodb-auto-increment-handling.html#innodb-auto-increment-initialization参考: https : //dev.mysql.com/doc/refman/5.7/en/innodb-auto-increment-handling.html#innodb-auto-increment-initialization

SELECT  table_schema, table_name, column_name, data_type, extra
    FROM  `columns`
    WHERE  table_schema = 'mydb'
      AND  extra LIKE '%auto_increment%' 

Optionally JOIN this with Alnitak's Answer.可以选择将其与 Alnitak 的回答一起JOIN

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

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