How to add a where clause in a MySQL Insert statement?

前端 未结 8 976
刺人心
刺人心 2020-11-30 12:56

This doesn\'t work:

INSERT INTO users (username, password) VALUES (\"Jack\",\"123\") WHERE id=\'1\';

Any ideas how to narrow insertion to a

相关标签:
8条回答
  • 2020-11-30 13:16

    I think you are looking for UPDATE and not insert?

    UPDATE `users`
    SET `username` = 'Jack', `password` = '123'
    WHERE `id` = 1
    
    0 讨论(0)
  • 2020-11-30 13:17
    INSERT INTO users (id,username, password) 
    VALUES ('1','Jack','123')
    ON DUPLICATE KEY UPDATE username='Jack',password='123'
    

    This will work only if the id field is unique/pk (not composite PK though) Also, this will insert if no id of value 1 is found and update otherwise the record with id 1 if it does exists.

    0 讨论(0)
  • 2020-11-30 13:21

    Try this:

    Update users
    Set username = 'Jack', password='123'
    Where ID = '1'
    

    Or if you're actually trying to insert:

    Insert Into users (id, username, password) VALUES ('1', 'Jack','123');
    
    0 讨论(0)
  • 2020-11-30 13:25

    In an insert statement you wouldn't have an existing row to do a where claues on? You are inserting a new row, did you mean to do an update statment?

    update users set username='JACK' and password='123' WHERE id='1';
    
    0 讨论(0)
  • 2020-11-30 13:27

    To add a WHERE clause inside an INSERT statement simply;

    INSERT INTO table_name (column1,column2,column3)
    SELECT column1, column2, column3 FROM  table_name
    WHERE column1 = 'some_value'
    
    0 讨论(0)
  • 2020-11-30 13:32

    For Empty row how we can insert values on where clause

    Try this

    UPDATE table_name SET username="",password="" WHERE id =""
    
    0 讨论(0)
提交回复
热议问题