简体   繁体   中英

Replace value from one column with a value from another columns

|Name    | FamilyName |
+--------+------------+
Penelopa | Crow       |
Mandarin | Overflow   |

I want to read Penelopa from "Name" and replace Crow value from "FamilyName" with Penelopa in a single query.

I do know that the Name I'm interested to use would be Penelopa as I do something like, and it exist.

SELECT "Name" FROM MyTable WHERE "Name" = 'Penelopa';

It's a basic update statement:

UPDATE MyTable
SET "FamilyName" = "Name"
WHERE "Name" = 'Penelopa' AND "FamilyName" = 'Crow'

To be sure that we are not replacing all family names with the name penelopa, but only the one for familyname Crow, I've included this condition in the WHERE statement.

One more thing to note would be that creating tables and columns with quotation marks " only makes it harder to code so I would avoid that.


To see your changes immediately without typing another query, you might add RETURNING * clause at the end of UPDATE query like this:

UPDATE MyTable
SET "FamilyName" = "Name"
WHERE "Name" = 'Penelopa' AND "FamilyName" = 'Crow'
RETURNING *

此SQL脚本可以执行您要执行的更新(用表名替换表):

update table set FamilyName=Name where Name='Penelopa';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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