How can I set a maximum number of rows in MySQL table?(如何设置 MySQL 表中的最大行数?)
问题描述
我需要在我的 MySQL 表中设置最大行数限制.文档告诉我们可以使用以下 SQL 代码来创建表:
I need to set a maximum limit of rows in my MySQL table. Documentation tell us that one can use following SQL code to create table:
CREATE TABLE `table_with_limit`
`id` int(11) DEFAULT NULL
) ENGINE=InnoDB MAX_ROWS=100000
但是 MAX_ROWS 属性不是硬性限制(存储不超过 100 000 行并删除其他行")而是对数据库引擎的提示,即该表将至少有 100 000 行.
But MAX_ROWS property is not a hard limit ("store not more then 100 000 rows and delete other") but a hint for database engine that this table will have AT LEAST 100 000 rows.
我认为解决问题的唯一可能方法是使用 BEFORE INSERT 触发器,该触发器将检查表中的行数并删除较旧的行.但我很确定这是一个巨大的过热:/
The only possible way I see to solve the problem is to use BEFORE INSERT trigger which will check the count of rows in table and delete the older rows. But I'm pretty sure that this is a huge overheat :/
另一种解决方案是每 N 分钟用 cron 脚本清除表.这是最简单的方法,但仍然需要另一个系统来监视.
Another solution is to clear the table with cron script every N minutes. This is a simplest way, but still it needs another system to watch for.
有人知道更好的解决方案吗?:)
Anyone knows a better solution? :)
推荐答案
尝试限制向表中添加新记录.将要添加新记录时引发错误.
Try to make a restriction on adding a new record to a table. Raise an error when a new record is going to be added.
DELIMITER $$
CREATE TRIGGER trigger1
BEFORE INSERT
ON table1
FOR EACH ROW
BEGIN
SELECT COUNT(*) INTO @cnt FROM table1;
IF @cnt >= 25 THEN
CALL sth(); -- raise an error
END IF;
END
$$
DELIMITER ;
请注意,COUNT 操作在大型 InnoDb 表上可能会很慢.
Note, that COUNT operation may be slow on big InnoDb tables.
在 MySQL 5.5 上,您可以使用 SIGNAL//RESIGNAL 语句引发错误.
On MySQL 5.5 you can use SIGNAL // RESIGNAL statement to raise an error.
这篇关于如何设置 MySQL 表中的最大行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何设置 MySQL 表中的最大行数?
基础教程推荐
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
