Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

PostgreSQL - How to add a new column with a default conditioning on another column?

I have a table like this

Table 1:

Code
 1
 2
 3
 4
 1
 2

I want to add a new column conditioning on the column code.

1 -> A
2 -> B
3 -> C
4 -> D

My expected result:

Table 1:

Code      Name
 1         A
 2         B
 3         C
 4         D
 1         A
 2         B

I expecting a code like this:

alter table table_1
add column Name varchar(64) set default case when Code = 1 then "A"
                                                  Code = 2 then "B"
                                                  Code = 3 then "C"
                                                  . . .

,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One straightforward way would be to just maintain a table of codes, and then join to it:

CREATE TABLE codes (Code integer, Name varchar(5));
INSERT INTO codes (Code, Name)
VALUES
    (1, 'A'),
    (2, 'B'),
    (3, 'C'),
    (4, 'D');

SELECT t1.Code, t2.Name
FROM table_1 t1
INNER JOIN codes t2
    ON t1.Code = t2.Code;

Note that I vote against doing this update, because as your underlying code values change, you might be forced to do the update again. The above approach doesn't have that problem, and you get the correct name when you select.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...