Skip to content Skip to sidebar Skip to footer

How To Create An "on-the-fly" Mapping Table Within A SELECT Statement In Postgresql

I'm creating a select statement that combines two tables, zone and output, based on a referenced device table and on a mapping of zone_number to output_type_id. The mapping of zo

Solution 1:

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;

Solution 2:

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.)


Solution 3:

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

Post a Comment for "How To Create An "on-the-fly" Mapping Table Within A SELECT Statement In Postgresql"