使用information_schema查找所有达到其限制的整数列

问题描述 投票:0回答:1

我可以获得我想要验证可用空间的所有列的列表。

SELECT 
  TABLE_NAME, COLUMN_NAME, COLUMN_TYPE 
FROM 
  INFORMATION_SCHEMA.COLUMNS 
WHERE 
  COLUMN_TYPE = 'int(11)' AND 
  TABLE_NAME LIKE 'catalog_category_entity%';

考虑到int(11)高达2147483648(不考虑未签名)我想计算我在这个范围内使用了多少。

我可以单独检查一个这样的:

select 
  max(value_id)/2147483648 as usage 
from 
  catalog_product_entity_int;

但是我希望对第一个查询中找到的所有列都做一个很好的方法。

我想知道在这种情况下递归CTE是否是正确的资源以及如何执行它或者是否有更优雅的方法来检查它。

我想在没有任何外部工具的情况下快速检查这种方法。

我找到了postgres的这个解决方案,但我想知道我是否真的需要这个功能。 postgres: find all integer columns with its current max value in it

mysql database-administration
1个回答
1
投票

我为这项任务写了一个解决方案,但我不是唯一一个做过这样的事情的人。

select concat('`', table_schema, '`.`', table_name, '`.`', column_name, '`') as `column`,
  auto_increment as `current_int`, max_int, round((auto_increment/max_int)*100, 2) as `pct_max`
from (select table_schema, table_name, column_name, auto_increment,
  pow(2, case data_type
    when 'tinyint'   then 7
    when 'smallint'  then 15
    when 'mediumint' then 23
    when 'int'       then 31
    when 'bigint'    then 63
    end+(column_type like '% unsigned'))-1 as max_int
  from information_schema.tables t
  join information_schema.columns c using (table_schema,table_name)
  join information_schema.key_column_usage k using (table_schema,table_name,column_name)
  where t.table_schema in ('test')
    and k.constraint_name = 'PRIMARY'
    and k.ordinal_position = 1
    and t.auto_increment is not null
) as dt;

https://github.com/billkarwin/bk-tools/blob/master/pk-full-ratio.sql

该查询是针对test架构的硬编码,因此您需要为自己的架构编辑它。

对“问题”的简短回答是“我的主要关键是要溢出吗?”现在就改变它到BIGINT UNSIGNED。这肯定会持续到文明崩溃。

在同一个git repo中,我有另一个类似的脚本来检查所有整数列,而不仅仅是自动增加主键。但对于其他专栏而言,这并不是一个问题。

© www.soinside.com 2019 - 2024. All rights reserved.