MySQL Insert Where query

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

    The right answer to this question will be sth like this:

    a). IF want select before insert :

    INSERT INTO Users( weight, desiredWeight ) 
      select val1 , val2  from tableXShoulatNotBeUsers
      WHERE somecondition;
    

    b). IF record already exists use update instead of insert:

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

    Should be

    Update Users set weight=160, desiredWeight=145  WHERE id = 1;
    

    c). If you want to update or insert at the same time

    Replace Users set weight=160, desiredWeight=145  WHERE id = 1;
    
    Note):- you should provide values to all fields else missed field in query 
            will be set to null
    

    d). If you want to CLONE a record from SAME table, just remember you cann't select from table to which you are inserting therefore

     create temporary table xtable ( weight int(11), desiredWeight int(11) ;
    
     insert into xtable (weight, desiredWeight) 
        select weight, desiredWeight from Users where [condition]
    
     insert into Users (weight, desiredWeight) 
        select weight , desiredWeight from xtable;
    

    I think this pretty covers most of the scenarios

提交回复
热议问题