How to evaluate expression in select statement in Postgres

后端 未结 2 1323
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 03:21

Postgres 9.1+ database contains customers and product. In customers table, customer price is described as sql expression in priceexpression column for every customer.

H

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-26 03:50

    you can write an SQL function that does this for you and use e.g. the ones supplied with postgres-utils:

    select 
      c.name as cust_name,
      p.name as prod_name,
      p.cost as prod_cost,
    
      eval(  
        'select '||c.price_expression||' from product where id=:pid',
        '{"{cost}",:pid}',  
        array[ p.cost, p.id ]  
      )      as cust_cost
    
    from product p,  customer c
    

    But of course it may be slow, insecure, you could use materialized views to cache it more easily, etc. - see docu there.

提交回复
热议问题