MySQL - Prevent Insertion of Record if ID and Timestamp Unique Combo Constraint Within Timeframe

China☆狼群 提交于 2019-12-02 13:28:42

If you're using MySQL 5.7 or newer, you can define a generated column that contains the timestamp rounded down to a 5 or 10 second range. Then you can define a unique index on that column, so you'll get a constraint violation if you try to create two records with timestamps in that same period.

ALTER TABLE yourTable 
ADD datetime_10sec INT AS (10 * ROUND(UNIX_TIMESTAMP(datetime)/10)) PERSISTENT, 
ADD UNIQUE INDEX (host_id, datetime_10sec);

Change both 10 to whatever time granularity you want to use.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!