2016-02-16 67 views
0

我有一個表:Postgres的加入兩條記錄到兩個引用一個記錄

Orders 
---- 
id 
amount 
price 

而第二臺

Order_Pairs 
---- 
id 
store_id 
order_id_buy (References id of order) 
order_id_sell (References id of order) 

我想在那裏我取了都買訂單記錄創建查詢並出售。

CREATE OR REPLACE FUNCTION test_func 

RETURNS TABLE 
(
jdoc JSON 
) AS $$ 

BEGIN 
    WITH i AS (
     SELECT * 
     FROM order_pairs 
      LEFT OUTER JOIN orders orders_buy ON order_pairs.order_id_buy = orders_buy.id 
      LEFT OUTER JOIN orders orders_sell ON order_pairs.order_id_sell = orders_sell.id 
     WHERE order_pairs.store_id = 1 
    ) 

    SELECT 
     ARRAY_TO_JSON(ARRAY_AGG(i.*)) 
    FROM i; 
END; $$ LANGUAGE plpgsql 

This works。除了當過程返回

ARRAY_TO_JSON(ARRAY_AGG(i.*)) 

我運行與公共列名(orders.id)重疊

我能夠讓每一個加盟記錄追加到orders_buy和orders_sell列名的字符或字段被提取?

+1

向我們展示了完整的程序。 –

+0

@a_horse_with_no_name已更新 –

+0

您寫道:'This works.',but your function does not return anything。你的Postgres版本也是必不可少的。 –

回答

0

假設在這裏你只需要得到關於每個order_pair記錄的全部細節。

輸入數據:

select * from orders; 
id | amount | price 
----+--------+------- 
    1 |  10 | 100 
    2 |  20 | 200 
(2 rows) 

select * from order_pairs; 
id | store_id | order_id_buy | order_id_sell 
----+----------+--------------+--------------- 
    3 |  10 |   1 |    2 
    4 |  20 |   1 |    1 
(2 rows) 

功能:

-- get order pair details by Store Id 
CREATE OR REPLACE FUNCTION get_order_pair_details(storeid INTEGER) RETURNS TABLE (jdoc JSON) AS $$ 
BEGIN 
    RETURN QUERY 
    WITH q AS (SELECT 
       op.id AS order_pair_id, 
       -- buyer info 
       ob.id AS buyer_id, 
       ob.price AS buyer_price, 
       ob.amount AS buyer_amount, 
       -- seller info 
       os.id AS sell_id, 
       os.price AS sell_price, 
       os.amount AS sell_amount 
       FROM order_pairs op 
       LEFT JOIN orders ob ON ob.id = op.order_id_buy 
       LEFT JOIN orders os ON os.id = op.order_id_sell 
       WHERE op.store_id = storeid) 
    SELECT array_to_json(array_agg(q.*)) FROM q; 
END; 
$$ LANGUAGE plpgsql; 

結果:

select get_order_pair_details(10) as result; 
                 result               
---------------------------------------------------------------------------------------------------------------------- 
[{"order_pair_id":3,"buyer_id":1,"buyer_price":100,"buyer_amount":10,"sell_id":2,"sell_price":200,"sell_amount":20}] 
(1 row) 
相關問題