John
John

Reputation: 1085

MySQL insert conditional datetime

I 'm wondering if it possible to insert records based on a specific date/time in one query without first selecting it.

For example:

I want to insert only when there is no record from 2 minutes ago.

How would this be achieved?

Thanks in advance

Upvotes: 0

Views: 325

Answers (1)

nosid
nosid

Reputation: 50054

Use the following statement instead of INSERT INTO table_name VALUES (1,'foobar'):

INSERT INTO foobar (foobar_id,display_name,ctime)
SELECT 42,'foobar',CURRENT_TIMESTAMP()
FROM DUAL
WHERE NOT EXISTS (
    SELECT 1
    FROM foobar
    WHERE mtime > CURRENT_TIMESTAMP() - INTERVAL 2 MINUTE
);

The trick is: Find a select statement, that returns a row with the columns to insert, if and only if the row should be inserted - and finally put INSERT INTO table_name in front of it. Note that the table DUAL is special table in MySQL and other DBMS.

Upvotes: 2

Related Questions