使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:28:55  来源:igfitidea点击:

inserting values into specific rows with SQL

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 INSERTstatementis only for creating completely new records, not for populating data into existing ones. What you need is an UPDATEstatement, 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 INSERTcan't take a WHEREclause, because WHERErefers to existing records, and an INSERTcreates 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 SELECTquery rather than by a VALUESexpression, and in that case the SELECTquery can, of course, have a WHEREclause. But in no case does the WHEREclause belong to the INSERTstatement directly.)

(为了防止潜在的混淆:存在这样的事情INSERT INTO ... SELECT ...,其中要插入的记录由SELECT查询而不是VALUES表达式确定,在这种情况下,SELECT查询当然可以有一个WHERE子句。但在任何情况下都不会WHERE子句INSERT直接属于语句。)