我的主键是一个整数。我在下一次插入时得到错误#1062-键"PRIMARY"的重复条目"4294967295"。
原因:显然达到了最大值。
有没有任何方法可以找到所有整列已达到最大值或接近最大值的表,以避免此类错误
查询:
SELECT
id, IF(max(id)<4294967295, 'true', 'false') as insert_flag
FROM Table
注意:我已经检查了上面的查询,max id的值是否小于则Int范围(4294967295)。查询在中返回true和falseinsert_flag列。您可以在插入之前在代码中检查此项。
如果您将id
视为某种AUTO_INCREMENT
字段,那么您可以获得所有具有show table status
的表的此信息(请使用help show table status
了解更多详细信息)。
例如
mysql> show table status G
*************************** 1. row ***************************
Name: test_table
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 65536
Data_free: 0
Auto_increment: 2
Create_time: 2014-11-07 13:17:16
Update_time: NULL
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
这里有一种方法可以检查所有自动递增列,看看它们离最大值有多近:
SELECT c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME,
(@max_auto_increment_size := CASE
WHEN c.COLUMN_TYPE like 'tinyint% unsigned' THEN 255
WHEN c.COLUMN_TYPE like 'tinyint%' THEN 127
WHEN c.COLUMN_TYPE like 'smallint% unsigned' THEN 65535
WHEN c.COLUMN_TYPE like 'smallint%' THEN 32767
WHEN c.COLUMN_TYPE like 'mediumint% unsigned' THEN 16777215
WHEN c.COLUMN_TYPE like 'mediumint%' THEN 8388607
WHEN c.COLUMN_TYPE like 'int% unsigned' THEN 4294967295
WHEN c.COLUMN_TYPE like 'int%' THEN 2147483647
WHEN c.COLUMN_TYPE like 'bigint% unsigned' THEN 18446744073709551615
WHEN c.COLUMN_TYPE like 'bigint%' THEN 9223372036854775807
ELSE 127
END) AS MAX_AUTO_INCREMENT_SIZE,
ROUND(@max_auto_increment_size - t.AUTO_INCREMENT) AS Headroom,
(CASE
WHEN ROUND(@max_auto_increment_size - t.AUTO_INCREMENT) < 1000 THEN 'CRITICAL'
WHEN ROUND(@max_auto_increment_size - t.AUTO_INCREMENT) < 10000 THEN 'LOW'
ELSE 'OK'
END) AS Remark
FROM information_schema.columns c
JOIN tables t ON (t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME)
WHERE c.TABLE_SCHEMA NOT IN('information_schema','mysql','performance_schema')
AND c.EXTRA = 'auto_increment'
ORDER BY c.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME;