MySQL Insert Where query

前端 未结 27 1807
悲&欢浪女
悲&欢浪女 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 07:00

    I am aware that this is a old post but I hope that this will still help somebody, with what I hope is a simple example:

    background:

    I had a many to many case: the same user is listed multiple times with multiple values and I wanted to Create a new record, hence UPDATE wouldn't make sense in my case and I needed to address a particular user just like I would do using a WHERE clause.

    INSERT into MyTable(aUser,aCar)
    value(User123,Mini)
    

    By using this construct you actually target a specific user (user123,who has other records) so you don't really need a where clause, I reckon.

    the output could be:

    aUser   aCar
    user123 mini
    user123 HisOtherCarThatWasThereBefore
    
    0 讨论(0)
  • 2020-11-22 07:01

    You can do conditional INSERT based on user input. This query will do insert only if input vars '$userWeight' and '$userDesiredWeight' are not blank

    INSERT INTO Users(weight, desiredWeight )
    select '$userWeight', '$userDesiredWeight'  
    FROM (select 1 a ) dummy
    WHERE '$userWeight' != '' AND '$userDesiredWeight'!='';
    
    0 讨论(0)
  • 2020-11-22 07:01

    You can do that with the below code:

    INSERT INTO table2 (column1, column2, column3, ...)
    SELECT column1, column2, column3, ...
    FROM table1
    WHERE condition
    
    0 讨论(0)
提交回复
热议问题