0

I've a problem, I want insert fields in a table if row not exist

My code is:

INSERT INTO  `myTable` (
`circuit` ,
`date` ,
`session` ,
`lap` ,
`time`
) SELECT  'misano',  '2013-10-11',  1,  1,  '0:01:06:332'
FROM `myTable`
WHERE NOT EXISTS (SELECT 1 FROM `myTable` WHERE `circuit` = 'misano' AND `date` = '2013-10-11' AND `session` = 1 AND `lap` = 1 AND `time` = '0:01:06:332')

This code work fine if in "myTable" there is at least one row. If "myTable" is empty, SQL return: 0 row.

2 Answers 2

5

If myTable is empty, then a SELECT ... FROM myTable will never produce any rows (even without the WHERE condition).

Use

FROM dual

in the outer select. The DUAL pseudo table always contains exactly one row. The EXISTS sub-query runs against myTable of course.

Edit:

If you have a unique index on myTable, see the solution suggested by Filipe.

Sign up to request clarification or add additional context in comments.

Comments

4

If you have a primary key or unique index in your table, you could use INSERT ... ON DUPLICATE KEY UPDATE

INSERT INTO `myTable` (`circuit`, `date`, `session`, `lap`, `time`)
    VALUES ('misano', '2013-10-11', 1, 1, '0:01:06:332') 
ON DUPLICATE KEY
UPDATE `circuit` = VALUES (`circuit`), 
        `date` = VALUES (`date`), 
        `session` = VALUES (`session`), 
        `lap` = VALUES (`lap`), 
        `time` = VALUES (`time`)

3 Comments

if a row exist this return a new same row with id=id+1
If the column with unique index already exists, this should update the old values for that record. But if you are excluding an auto_incremented id, then yes, that will always insert and never update, since you are saying you want a different id for this row, thus never triggering the update.
however I do not have an index, thank's for your patience. Fabian Büttner solution is perfect for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.