仅在5分钟后插入访问

时间:2018-03-12 00:24:32

标签: mysql sql

我想插入这样的访问:

id - user - visit - data
1 - 1 - 2 - date
2 - 1 - 3 - date
3 - 1 - 2 - date after 5 minutes from the first (id 1) - only insert if it has pasted more than 5 minutes from the last similar record.

用户1访问了用户2和3。 问题是,我想在前5分钟内插入访问而不重复访问。在此之后我想插入。

我试过了:

INSERT INTO visits (user, visit, data) 
SELECT '1', '2', NOW() WHERE NOT EXISTS (SELECT 1 FROM visits WHERE user = '1' AND visit = '2' AND data >= DATE_SUB(NOW(), INTERVAL 5 MINUTE))

但它不起作用。任何想法?

1 个答案:

答案 0 :(得分:2)

您可以在insert

中表达逻辑
INSERT INTO visits (user, visit, data) 
    SELECT u.user, u.visit, u.data
    FROM (SELECT 1 as user, 2 as visit, NOW() as data) u
    WHERE NOT EXISTS (SELECT 1
                      FROM visits v
                      WHERE v.user = u.user AND v.visit = u.visit AND
                            u.data >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
                     );

这解决了特定INSERT的问题。这可能足够好了。但是,您依靠应用程序来确保数据完整性。触发器可确保不会发生违反规则的插入或更新。