如何在 MySQL Insert 语句中添加 where 子句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2349993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a where clause in a MySQL Insert statement?
提问by Zack
This doesn't work:
这不起作用:
INSERT INTO users (username, password) VALUES ("Hyman","123") WHERE id='1';
Any ideas how to narrow insertion to a particular row by id?
任何想法如何通过 id 缩小对特定行的插入?
回答by broschb
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?
在插入语句中,您不会有一个现有的行来执行 where claues 吗?您正在插入一个新行,您的意思是要执行更新语句吗?
update users set username='Hyman' and password='123' WHERE id='1';
回答by gerrit_hoekstra
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:
在这个例子中,只有第二个 insert-statement 才会真正将数据插入到表中:
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)
回答by Jonathan
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'
回答by Nick Craver
Try this:
尝试这个:
Update users
Set username = 'Hyman', password='123'
Where ID = '1'
Or if you're actually trying to insert:
或者,如果您实际上是在尝试插入:
Insert Into users (id, username, password) VALUES ('1', 'Hyman','123');
回答by jasonbar
回答by Itay Moav -Malimovka
INSERT INTO users (id,username, password)
VALUES ('1','Hyman','123')
ON DUPLICATE KEY UPDATE username='Hyman',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)时才有效。此外,如果没有id
找到值 1 ,这将插入,否则id
如果确实存在,则用1更新记录。
回答by RajeeV VenkaT
UPDATE users SET username='&username', password='&password' where id='&id'
This query will ask you to enter the username,password and id dynamically
此查询将要求您动态输入用户名、密码和 ID
回答by Prasad MCN
For Empty row how we can insert values on where clause
对于空行,我们如何在 where 子句上插入值
Try this
尝试这个
UPDATE table_name SET username="",password="" WHERE id =""