且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何实时检查是否在MySQL表中添加了新行

更新时间:2021-09-10 07:22:38

如果您的表是MyISAM,我会坚持您的最初想法.从MyISAM表获取行数是即时的. MyISAM始终保持行数,因此只读取一个值即可.

If your table is MyISAM, I would stick to your initial idea. Getting the row count from a MyISAM table is instant. It only takes the reading of one single value as MyISAM maintains the row count at all times.

对于InnoDB,这种方法仍然可以接受.假设car_table.id是主键,则SELECT COUNT(id) FROM car_table仅需要索引扫描,这非常快.您可以通过向表中添加另一个索引的布尔列来改进此想法:

With InnoDB, this approach can still be acceptable. Assuming car_table.id is primary key, SELECT COUNT(id) FROM car_table only requires an index scan, which is very fast. You can improve on this idea by adding another indexed boolean column to your table:

ALTER car_table ADD COLUMN checked BOOLEAN NOT NULL DEFAULT 0, ADD INDEX (checked);

默认值可确保在不修改插入语句的情况下将此标志设置为0插入新车.然后:

The default value ensures new cars will be inserted with this flag set to 0 without modifying the inserting statement. Then:

BEGIN TRANSACTION; -- make sure nobody interferes
SELECT COUNT(checked) FROM car_table WHERE checked = FALSE FOR UPDATE; -- this gets you the number of new, unchecked cars
UPDATE car_table SET checked = TRUE WHERE checked = FALSE; -- mark these cars as checked
COMMIT;

这样,您每次轮询仅扫描很少数量的索引条目.

This way, you only scan a very small number of index entries at each polling.

一种更高级的方法是通过触发器将新创建的汽车ID添加到边桌中.在不锁定主表且不更改其结构的情况下,不时扫描此边桌.每次轮询后只需TRUNCATE此边桌即可.

A more advanced approach consists in adding newly created cars ID's into a side table, through a trigger. This side table is scanned every now and then, without locking the main table, and without altering its structure. Simply TRUNCATE this side table after each polling.

最后,正如Panagiotis所建议的那样,可以选择触发UDF,但这在大多数情况下似乎是过大的选择.

Finally, there is the option of triggering a UDF, as suggested by Panagiotis, but this seems to be an overkill in most situations.