简体   繁体   English

如何在MySQL Insert语句中添加where子句?

[英]How to add a where clause in a MySQL Insert statement?

This doesn't work: 这不起作用:

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

Any ideas how to narrow insertion to a particular row by id? 任何想法如何通过id将插入范围缩小到特定行?

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';

A conditional insert for use typically in a MySQL script would be: 通常在MySQL脚本中使用的条件插入为:

insert into t1(col1,col2,col3,...)
select val1,val2,val3,...
  from dual
 where [conditional predicate];

You need to use dummy table dual. 您需要使用双重虚拟表。

In this example, only the second insert-statement will actually insert data into the table: 在此示例中,仅第二个插入语句将实际将数据插入表中:

create table t1(col1 int);
insert into t1(col1) select 1 from dual where 1=0;
insert into t1(col1) select 2 from dual where 1=1;
select * from t1;
+------+
| col1 |
+------+
|    2 |
+------+
1 row in set (0.00 sec)

To add a WHERE clause inside an INSERT statement simply; 只需在INSERT语句内添加WHERE子句;

INSERT INTO table_name (column1,column2,column3)
SELECT column1, column2, column3 FROM  table_name
WHERE column1 = 'some_value'

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');

I think you are looking for UPDATE and not insert? 我认为您正在寻找UPDATE而不是插入?

UPDATE `users`
SET `username` = 'Jack', `password` = '123'
WHERE `id` = 1
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. 仅当id字段为唯一/ pk(尽管不是复合PK)时,此方法才有效。此外,如果未找到值为1的id ,则将插入该字段;如果存在,则更新id 1的记录。

UPDATE users SET username='&username', password='&password' where id='&id'

该查询将要求您动态输入用户名,密码和ID

For Empty row how we can insert values on where clause 对于空行,我们如何在where子句中插入值

Try this 尝试这个

UPDATE table_name SET username="",password="" WHERE id =""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM