简体   繁体   中英

How to assign the result of a SELECT as a table column in sql?

I have the following table (table_test) in the postgres database:

      id         value         description
     -----------------------------------------
     741         1             'description X'
     152         2             'description X'
     555         1             'description X'

I need to create a new column in this table. The new column should receive the column value 'value' multiplied by 1000 and divided by 3.

First I created a new column called 'new_column'

ALTER TABLE table_test
    ADD new_column float(10)

Next, I did the desired operation with a SELECT:

SELECT ((value * 1000) / 3)
FROM table_test

The problem arose when I tried to duplicate the SELECT result in the newly created column. I tried to do (not working):

UPDATE table_test
SET new_column = (SELECT ((value * 1000) / 3)
                  FROM table_test)

The error message that appears is:

ERROR: more than one row returned by a subquery used as an expression
SQL state: 21000

I would like the output to be:

        id         value          description         new_column
        --------------------------------------------------------
        741         1             'description X'        333
        152         2             'description X'        666
        555         1             'description X'        333

You can add a computed column instead:

ALTER TABLE table_test ADD new_column float GENERATED ALWAYS AS
    (value * 10000 / 3.0) stored;

This means the value is always up-to-date.

If you just want to set the value, though, the update for a non-generated column is simply:

UPDATE table_test
    SET new_column = value * 1000 / 3.0;

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