How to create an “on-the-fly” mapping table within a SELECT statement in Postgresql

江枫思渺然 提交于 2019-11-30 12:45:17

You can use VALUES as an inline table and JOIN to it, you just need to give it an alias and column names:

join (values (1, 101), (2, 202), (3, 303), (4, 304)) as map(zone_number, output_type_id)
on ...

From the fine manual:

VALUES can also be used where a sub-SELECT might be written, for example in a FROM clause:

SELECT f.*
  FROM films f, (VALUES('MGM', 'Horror'), ('UA', 'Sci-Fi')) AS t (studio, kind)
  WHERE f.studio = t.studio AND f.kind = t.kind;

UPDATE employees SET salary = salary * v.increase
  FROM (VALUES(1, 200000, 1.2), (2, 400000, 1.4)) AS v (depno, target, increase)
  WHERE employees.depno = v.depno AND employees.sales >= v.target;

So just to complement the accepted answer, the following code is a valid, self-contained Postgresql expression which will evaluate to an 'inline' relation with columns (zone_number, output_type_id):

SELECT * FROM 
(VALUES 
  (1, 101), 
  (2, 202), 
  (3, 303), 
  (4, 304)
) as i(zone_number, output_type_id)

(The (VALUES ... AS ...) part alone will not make a valid expression, which is why I added the SELECT * FROM.)

JOIN 
(SELECT 1 zone_number, 101 as output_type_id
 UNION ALL
 SELECT 2 zone_number, 202 as output_type_id
 UNION ALL
 SELECT 3 zone_number, 303 as output_type_id
) mappings on mappings.zone_number = zone.zone_number
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!