MySQL SQL 设置一列的值等于同一表中另一列的值

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

SQL set values of one column equal to values of another column in the same table

mysqlsql

提问by user1002358

I have a table with two DATETIME columns.

我有一个包含两个 DATETIME 列的表。

One of them is never NULL, but one of them is sometimes NULL.

其中之一从不为 NULL,但其中之一有时为 NULL。

I need to write a query which will set all the NULL rows for column B equal to the values in column A.

我需要编写一个查询,它将 B 列的所有 NULL 行设置为 A 列中的值。

I have tried this examplebut the SQL in the selected answer does not execute because MySQL Workbench doesn't seem to like the FROM in the UPDATE.

我已经尝试过这个例子,但是所选答案中的 SQL 没有执行,因为 MySQL Workbench 似乎不喜欢 UPDATE 中的 FROM。

回答by mu is too short

Sounds like you're working in just one table so something like this:

听起来你只是在一张桌子上工作,所以是这样的:

update your_table
set B = A
where B is null

回答by Icarus

UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL 
AND ColumnA IS NOT NULL

回答by Bill Karwin

I would do it this way:

我会这样做:

UPDATE YourTable SET B = COALESCE(B, A);

COALESCE is a function that returns its first non-null argument.

COALESCE 是一个返回其第一个非空参数的函数。

In this example, if B on a given row is not null, the update is a no-op.

在此示例中,如果给定行上的 B 不为空,则更新为空操作。

If B is null, the COALESCE skips it and uses A instead.

如果 B 为空,则 COALESCE 跳过它并使用 A 代替。

回答by rwilliams

I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.

我不认为其他例子是你正在寻找的。如果您只是从同一表中的另一列更新一列,您应该能够使用这样的东西。

update some_table set null_column = not_null_column where null_column is null

回答by Waruna Manjula

Here is sample code that might help you coping Column A to Column B:

以下是可以帮助您处理 A 列到 B 列的示例代码:

UPDATE YourTable
SET ColumnB = ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL;