MySQL Insert Where query

前端 未结 27 1806
悲&欢浪女
悲&欢浪女 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:52

    After WHERE clause you put a condition, and it is used for either fetching data or for updating a row. When you are inserting data, it is assumed that the row does not exist.

    So, the question is, is there any row whose id is 1? if so, use MySQL UPDATE, else use MySQL INSERT.

    0 讨论(0)
  • 2020-11-22 06:53

    You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware-

    1. INSERT specifying values

      INSERT INTO Users(weight, desiredWeight) 
      VALUES (160,145)
      
    2. INSERT using a SELECT statement

      INSERT INTO Users(weight, desiredWeight) 
      SELECT weight, desiredWeight 
      FROM AnotherTable 
      WHERE id = 1
      
    0 讨论(0)
  • 2020-11-22 06:53

    Insert into = Adding rows to a table

    Upate = update specific rows.

    What would the where clause describe in your insert? It doesn't have anything to match, the row doesn't exist (yet)...

    0 讨论(0)
  • 2020-11-22 06:55

    You simply cannot use WHERE when doing an INSERT statement:

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

    should be:

     INSERT INTO Users( weight, desiredWeight ) VALUES ( 160, 145 );
    

    The WHERE part only works in SELECT statements:

    SELECT from Users WHERE id = 1;
    

    or in UPDATE statements:

    UPDATE Users set (weight = 160, desiredWeight = 145) WHERE id = 1;
    
    0 讨论(0)
  • 2020-11-22 06:55
    INSERT INTO Users(weight, desiredWeight )
    SELECT '$userWeight', '$userDesiredWeight'  
    FROM (select 1 a ) dummy
    WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
    
    0 讨论(0)
  • 2020-11-22 06:56

    You Should not use where condition in Insert statement. If you want to do, use insert in a update statement and then update a existing record.

    Actually can i know why you need a where clause in Insert statement??

    Maybe based on the reason I might suggest you a better option.

    0 讨论(0)
提交回复
热议问题