如果您使用MySQL 5.7.6或更高版本,您可以創建一個具有唯一索引的生成列。
ALTER TABLE table_name
ADD COLUMN timestamp_date DATE GENERATED ALWAYS AS (DATE(timestamp)) STORED,
ADD UNIQUE (timestamp_date, action, value);
隨着MySQL的早期版本,你需要添加一列來存儲日期和使用觸發器(可從5.0.2版本)來更新它,每當你在表中插入新記錄。
ALTER TABLE table_name
ADD COLUMN timestamp_date DATE;
CREATE TRIGGER insert_table_name_date BEFORE INSERT ON table_name
FOR EACH ROW SET NEW.timestamp_date = DATE(NEW.timestamp);
-- If you already have any data in the table, update it to add the date.
UPDATE table_name SET timestamp_date = DATE(timestamp_date);
ALTER TABLE table_name
ADD UNIQUE (timestamp_date, action, value);
INSERT INTO table_name(timestamp, action, value) VALUES
('2016-04-21 13:33:47', 'send', 'email'),
('2016-04-20 11:21:32', 'send', 'email'),
('2016-04-19 17:32:55', 'send', 'email');
-- 3 row(s) affected
INSERT INTO table_name(timestamp, action, value) VALUES
('2016-04-21 19:33:47', 'send', 'email');
-- Error Code: 1062. Duplicate entry '2016-04-21-send-email' for key 'timestamp_date'
順便說一句,2016-04-19 17:32:65不是一個有效的時間戳。我假設秒是一個錯字。 –