MySQL 将相同的固定值插入多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4693173/
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-08-31 18:19:51  来源:igfitidea点击:

Insert the same fixed value into multiple rows

mysqlsqlsql-updatesql-insert

提问by TheDelChop

I've got a table with a column, lets call it table_columnthat is currently nullfor all rows of the table. I'd like to insert the value "test"into that column for all rows. Can someone give me the SQL for this?

我有一个带有一列的表格,我们称之为table_column当前null适用于表格的所有行。我想将"test"所有行的值插入到该列中。有人可以给我 SQL 吗?

I've tried INSERT INTO table (table_column) VALUES ("test");but that only populates that last row. How do I do all of the rows at once?

我试过,INSERT INTO table (table_column) VALUES ("test");但只填充最后一行。如何一次完成所有行?

回答by Brad Christie

You're looking for UPDATEnot insert.

您正在寻找UPDATE而不是插入。

UPDATE mytable
SET    table_column = 'test';

UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).

UPDATE 将更改现有行的值(并且可以包含一个 WHERE 以使其仅影响特定行),而 INSERT 正在添加一个新行(这使它看起来只更改了最后一行,但实际上是添加了一个新行)具有该值的行)。

回答by DVK

This is because in relational database terminology, what you want to do is not called "inserting", but "UPDATING" - you are updating an existing row's field from one value (NULL in your case) to "test"

这是因为在关系数据库术语中,您想要做的不是“插入”,而是“更新” - 您正在将现有行的字段从一个值(在您的情况下为 NULL)更新为“测试”

UPDATE your_table SET table_column = "test" 
WHERE table_column = NULL 

You don't need the second line if you want to update 100% of rows.

如果要更新 100% 的行,则不需要第二行。

回答by Nicolas Buduroi

What you're actually doing is adding rows. To update the content of existing rows use the UPDATE statement:

你实际上在做的是添加行。要更新现有行的内容,请使用 UPDATE 语句:

UPDATE table SET table_column = 'test';

回答by Sani Kamal

To update the content of existing rows use the UPDATEstatement:

要更新现有行的内容,请使用以下UPDATE语句:

UPDATE table_name SET table_column = 'test';

回答by Damodharan R

UPDATE `table` SET table_column='test';

回答by James Lelyveld

The SQL you need is:

您需要的 SQL 是:

Update table set table_column = "test";

The SQL you posted creates a new row rather than updating existing rows.

您发布的 SQL 创建一个新行而不是更新现有行。

回答by jeppoo1

To create a new empty column and fill it with the same value (here 100) for every row (in Toad for Oracle):

要为每一行(在 Toad for Oracle 中)创建一个新的空列并使用相同的值(此处为 100)填充它:

ALTER TABLE my_table ADD new_column INT;
UPDATE my_table SET new_column = 100;