2

For some reason my script isn't deleting existing rows when I'm using replace.

I'm working on an inventory management system, and I may be calling this script every hour or so to update the db:

   REPLACE INTO inventory(username, sku,asin,set_price,inventory)
                   VALUES('trav','AEG5502','B00875JE0C','23.49','');

but instead of deleting the old row, it creates a new row with the exact same info.

I'm sure it's a simple error, but I would love if someone could help me out.

Additional info, a row has about 15 columns. None of these columns (username, sku,asin,set_price,inventory) are a primary key, I don't know if that has to be the case for replace to work, but I thought I'd mention it.

Thanks

3
  • REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. Commented Mar 20, 2013 at 6:44
  • 1
    Offtopic. But I see you insert a username into the row. It's wiser to include a user_id instead of a name. What if the username changes? Commented Mar 20, 2013 at 6:46
  • @bart: assuming proper foreign key setups, you can cascade such a change. Commented Mar 20, 2013 at 13:54

1 Answer 1

4

RTLM: http://dev.mysql.com/doc/refman/5.0/en/replace.html replace will only replace if ANY of the fields you're using are the primary or at least a unique key in the table. since none of your fields are, it simply does an insert

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

2 Comments

Shoot, I guess I didn't think about that when I setup the database. Thanks for the help though! Is there any way to simulate a sku being unique if username = trav? I'm guessing that some users will have the same sku numbers.
offhand guess: slap a unique index on the (username,sku) tuple?

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.