MySQL Insert Where query

前端 未结 27 2226
悲&欢浪女
悲&欢浪女 2020-11-22 06:16

What\'s wrong with this query:

INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 ) WHERE id = 1;

It works without the WHE

27条回答
  •  深忆病人
    2020-11-22 06:59

    You use the WHERE clause for UPDATE queries. When you INSERT, you are assuming that the row doesn't exist.

    The OP's statement would then become;

    UPDATE Users SET weight = 160, desiredWeight = 45 where id = 1;

    In MySQL, if you want to INSERT or UPDATE, you can use the REPLACE query with a WHERE clause. If the WHERE doesn't exist, it INSERTS, otherwise it UPDATES.

    EDIT

    I think that Bill Karwin's point is important enough to pull up out of the comments and make it very obvious. Thanks Bill, it has been too long since I have worked with MySQL, I remembered that I had issues with REPLACE, but I forgot what they were. I should have looked it up.

    That's not how MySQL's REPLACE works. It does a DELETE (which may be a no-op if the row does not exist), followed by an INSERT. Think of the consequences vis. triggers and foreign key dependencies. Instead, use INSERT...ON DUPLICATE KEY UPDATE.

提交回复
热议问题