mysql通过触发器设置最大行数 [英] mysql setting max number of rows with a trigger
本文介绍了mysql通过触发器设置最大行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个最多包含5行的表.因此,如果我添加新行并且表已经有5行,则触发器应删除第一行并添加新行.
I want to create a table that should have max 5 rows. So if I add a new row and the table already have 5 rows, the trigger should delete the first row and add the new row.
例如:
my_table
id | data
---------
1 | a
---------
2 | b
---------
3 | c
---------
4 | d
更改为
my_table
id | data
---------
2 | b
---------
3 | c
---------
4 | d
---------
5 | e
推荐答案
您可以使用触发器来做到这一点:
You can do that with a trigger:
CREATE TRIGGER handleFiveRows BEFORE INSERT ON tableName
FOR EACH ROW
BEGIN
IF (SELECT COUNT(*) FROM tableName) = 5 THEN
DELETE FROM tableName
ORDER BY id
LIMIT 1;
END IF;
END;
每当您有5行时,这将删除ID最小的行,并且在插入后您将再次以5行结束.
Whenever you have 5 rows, this will delete the row with the smallest id and after your insert you will end up with 5 rows again.
这篇关于mysql通过触发器设置最大行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文