Martin
Martin

Reputation: 40

SQL INSERT new row if columns values don't exist

I'm having a little trouble with my SQL queries and I keep getting a syntax error I can't figure out.

The query in question is:

INSERT INTO $db (uuid, quest, stage, completion, quest_id, dstart) VALUES ('".$avatar_key."','".$quest_name."','".$quest_stage."','".$qc."','".$quest_id."','".$date."') WHERE NOT EXISTS (SELECT *
       FROM $db
       WHERE uuid = '$avatar_key' AND quest_id = '$quest_id'
       )

What I'm trying to do is to check if the table has a row, with both the exact values of $avatar_key and $quest_id, and if such a row does NOT exist, then I want it to INSERT a new one.

I'm getting an error I can't seem to figure out how to fix though; the query itself looks to me (though I'm a SQL newbie) that is /should/ work. I'm using SQL 5.5, & this is the error message I'm getting:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT * FROM sldb_quest WHERE uuid = '0089dcea-' at line 1

I know that having a unique identifier would've helped that, but the database is going to store a LOT of rows, many of which will have identical values and the only unique value will be the UUID, which I must then match up with the quest_id in order to find the specific row I want. The uuids look something like this: "0089dcea-bf39-40f5-859e-d79bdc383f1b" and are uniquely generated for every user.

Any pointers as to what I'm doing wrong would be very appreciated! I'm sure it's just a small detail I've managed to miss somewhere, but I've not had any luck finding the cause.

Upvotes: 0

Views: 1464

Answers (1)

PinnyM
PinnyM

Reputation: 35533

A WHERE clause is not valid on a INSERT with a VALUES list. You can use INSERT ... ON DUPLICATE UPDATE, but I'm not sure an update is what you want.

If uuid (with or without quest_id) is set as a unique key, the simplest thing you can try is to use IGNORE.

INSERT IGNORE INTO $db (uuid, quest, stage, completion, quest_id, dstart) 
VALUES ('".$avatar_key."','".$quest_name."','".$quest_stage."','".$qc."','".$quest_id."','".$date."')

And if you don't have a unique key yet, I strongly recommend you make one.

Upvotes: 1

Related Questions