MySQL Insert Where query

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

    No. As far as I am aware you cannot add the WHERE clause into this query. Maybe I've forgotten my SQL too, because I am not really sure why you need it anyway.

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

    A way to use INSERT and WHERE is

    INSERT INTO MYTABLE SELECT 953,'Hello',43 WHERE 0 in (SELECT count(*) FROM MYTABLE WHERE myID=953); In this case ist like an exist-test. There is no exception if you run it two or more times...

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

    MySQL INSERT Syntax does not support the WHERE clause so your query as it stands will fail. Assuming your id column is unique or primary key:

    If you're trying to insert a new row with ID 1 you should be using:

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

    If you're trying to change the weight/desiredWeight values for an existing row with ID 1 you should be using:

    UPDATE Users SET weight = 160, desiredWeight = 145 WHERE id = 1;
    

    If you want you can also use INSERT .. ON DUPLICATE KEY syntax like so:

    INSERT INTO Users (id, weight, desiredWeight) VALUES(1, 160, 145) ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145
    

    OR even like so:

    INSERT INTO Users SET id=1, weight=160, desiredWeight=145 ON DUPLICATE KEY UPDATE weight=160, desiredWeight=145
    

    It's also important to note that if your id column is an autoincrement column then you might as well omit it from your INSERT all together and let mysql increment it as normal.

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

    correct syntax for mysql insert into statement using post method is:

    $sql="insert into ttable(username,password) values('$_POST[username]','$_POST[password]')";
    
    0 讨论(0)
  • 2020-11-22 06:42

    If you are specifying a particular record no for inserting data its better to use UPDATE statement instead of INSERT statement.

    This type of query you have written in the question is like a dummy query.

    Your Query is :-

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

    Here , you are specifying the id=1 , so better you use UPDATE statement to update the existing record.It is not recommended to use WHERE clause in case of INSERT.You should use UPDATE .

    Now Using Update Query :-

    UPDATE Users SET weight=160,desiredWeight=145 WHERE id=1;
    
    0 讨论(0)
  • 2020-11-22 06:43

    i dont think that we can use where clause in insert statement

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