我有一张桌子:
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
我想创建一个查询,我可以获取买卖的两个订单记录。
ARRAY_TO_JSON(ARRAY_AGG(i.*))
这很有效。除非程序返回
let headerStyle = {
backgroundImage : "url('about.jpg')"
};
我遇到与常见列名称(orders.id)
的重叠我能够让每个连接记录在提取的orders_buy和orders_sell列名中追加一个字符或字段吗?
答案 0 :(得分: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)