使用 SQL 将值插入特定行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8334918/
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
inserting values into specific rows with SQL
提问by Matt
I Have a table of bike details and I want to add different prices to different bike types using SQL queries, but what I have gives me a syntax error:
我有一个自行车详细信息表,我想使用 SQL 查询为不同的自行车类型添加不同的价格,但是我所拥有的给了我一个语法错误:
INSERT INTO bike (full_day)
VALUES (10)
WHERE bike_type = 'mens_hybrid';
What is wrong with this code?
这段代码有什么问题?
回答by ruakh
An INSERT
statementis only for creating completely new records, not for populating data into existing ones. What you need is an UPDATE
statement, which updates an existing record:
一种INSERT
说法是只为创造全新的记录,而不是将数据填充到现有的。您需要的是一条UPDATE
语句,它更新现有记录:
UPDATE bike SET full_day = 10 WHERE bike_type = 'mens_hybrid';
(Note: below is an earlier version of this answer, from before it was clear to me what the original poster was trying to do. I'm leaving it here because multiple people who originally answered this question did not seem to notice the problem with writing INSERT ... VALUES (...) WHERE
, which makes me think that this explanation might be useful to some people coming across this question.)
(注意:下面是这个答案的早期版本,在我很清楚原始海报试图做什么之前。我把它留在这里是因为最初回答这个问题的多个人似乎没有注意到这个问题写作INSERT ... VALUES (...) WHERE
,这让我觉得这个解释可能对遇到这个问题的一些人有用。)
That statement doesn't make sense. An INSERT
can't take a WHERE
clause, because WHERE
refers to existing records, and an INSERT
creates new ones.
这种说法没有意义。AnINSERT
不能带WHERE
子句,因为WHERE
引用现有记录,而 anINSERT
创建新记录。
(To forestall potential confusion: there exists such a thing as INSERT INTO ... SELECT ...
, where the records to insert are determined by a SELECT
query rather than by a VALUES
expression, and in that case the SELECT
query can, of course, have a WHERE
clause. But in no case does the WHERE
clause belong to the INSERT
statement directly.)
(为了防止潜在的混淆:存在这样的事情INSERT INTO ... SELECT ...
,其中要插入的记录由SELECT
查询而不是VALUES
表达式确定,在这种情况下,SELECT
查询当然可以有一个WHERE
子句。但在任何情况下都不会WHERE
子句INSERT
直接属于语句。)