简体   繁体   English

SQL - 在同一个表中将数据从一列复制到另一列

[英]SQL - Copy data from one column to another in the same table

I have a table with 1000+ rows and I am trying to copy data from one column to another, for all rows.我有一个包含 1000 多行的表,我正在尝试将所有行的数据从一列复制到另一列。

This is my table "Invoice":这是我的“发票”表:

example1示例1 example 2示例 2
A一个 NULL NULL
B NULL NULL
C C NULL NULL

Expected end result should be:预期的最终结果应该是:

example1示例1 example 2示例 2
A一个 A一个
B B
C C C C

What I tried so far:到目前为止我尝试了什么:

UPDATE "Invoice" 
SET "example1" = copiedData
FROM (SELECT "example2" FROM "Invoice") AS copiedData;

This does update all rows but the issue is that it does not update row for row, instead it picks up a random row from the sub query and applies it to all rows.这确实会更新所有行,但问题是它不会逐行更新,而是从子查询中选择随机行并将其应用于所有行。

Example of how the current result looks like:当前结果的示例:

example1示例1 example 2示例 2
A一个 B
B B
C C B

What am I missing here?我在这里想念什么?

Thank you.谢谢你。

What you want is much simpler:你想要的要简单得多:

UPDATE "Invoice" 
    SET "example2" = "example1";

Note: I would strongly encourage you to remove the double quotes.注意:我强烈建议您删除双引号。 Don't escape column names -- it just makes it harder to write and to read the code.不要转义列名——它只会让编写和阅读代码变得更加困难。

You just need to update Invoice table's example2 column with example1.您只需使用 example1 更新 Invoice 表的 example2 列。

UPDATE Invoice 
SET example2 = example1;

If you only want to update example2 column when it's null then you will need a where clause also.如果您只想在 example2 为 null 时更新它,那么您还需要一个 where 子句。

UPDATE Invoice 
SET example2 = example1 where example2 is null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM