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

前端 未结 3 1856
南方客
南方客 2020-12-16 00:30

I\'m creating a select statement that combines two tables, zone and output, based on a referenced device table and on a mapping of

相关标签:
3条回答
  • 2020-12-16 00:46

    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;
    
    0 讨论(0)
  • 2020-12-16 00:54

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

    0 讨论(0)
  • 2020-12-16 01:02
    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
    
    0 讨论(0)
提交回复
热议问题