I have this query, which should insert an amount if an amount equals or higher for the same ID doesn’t already exists in the table.
I tried this under MySQL 5.1 and MSSQL 2k5 :
MySQL
INSERT IGNORE INTO test (id, amount)
SELECT 6, 50 FROM test
WHERE NOT EXISTS (SELECT 1 FROM test WHERE amount >= 50 AND id = 6) LIMIT 1
MSSQL
INSERT INTO test (id, amount)
SELECT 6, 50 FROM test
WHERE NOT EXISTS (SELECT TOP 1 1 FROM test WHERE amount >= 50 AND id = 6)
This query works fine IF there is already at least one entry in the table. If the table is empty, it will never work. It’s the same behavior under MySQL (5.1) and MSSQL (2005).
I don’t understand why. Anybody has an explanation and a way to fix this query to work even if the table is completely empty?
EDIT : I need this for MySQL mostly…
UPDATE : I started a new question specifically for MySQL :
MySQL Problem with inserting a row with certain conditions
It fails because the select statement selects values of 6 and 50 based on the number of rows returned. Since your table is empty – no rows are returned to have these values.
Modify it to