10

I want to select from an enumaration that is not in database.

E.g. SELECT id FROM my_table returns values like 1, 2, 3 I want to display 1 -> 'chocolate', 2 -> 'coconut', 3 -> 'pizza' etc. SELECT CASE works but is too complicated and hard to overview for many values. I think of something like

SELECT id, array['chocolate','coconut','pizza'][id] FROM my_table

But I couldn't succeed with arrays. Is there an easy solution? So this is a simple query, not a plpgsql script or something like that.

4

3 回答 3

10
with food (fid, name) as (
  values 
     (1, 'chocolate'),
     (2, 'coconut'),
     (3, 'pizza')
)
select t.id, f.name
from my_table t
  join food f on f.fid = t.id;

或没有 CTE(但使用相同的想法):

select t.id, f.name
from my_table t
  join (
     values 
       (1, 'chocolate'),
       (2, 'coconut'),
       (3, 'pizza')
  ) f (fid, name) on f.fid = t.id;
于 2013-04-04T18:29:15.710 回答
4

这是正确的语法:

SELECT id, (array['chocolate','coconut','pizza'])[id] FROM my_table

但是您应该使用这些值创建一个引用表。

于 2013-04-04T18:36:13.740 回答
0

创建另一个表来枚举所有情况并进行连接怎么样?

CREATE TABLE table_case
(
  case_id bigserial NOT NULL,
  case_name character varying,
  CONSTRAINT table_case_pkey PRIMARY KEY (case_id)
)
WITH (
  OIDS=FALSE
);

当您从表中选择时:

SELECT id, case_name FROM my_table 
inner join table_case on case_id=my_table_id;
于 2013-04-04T18:00:54.283 回答