联接2在一个查询中进行选择

时间:2019-02-13 10:33:54

标签: sql postgresql

如何在一个查询中加入这两个选择?

SELECT st.tracking_id FROM sale_order_line_tracking AS st, sale_order_line AS sol 
WHERE st.order_line_id = sol.id
AND sol.id in %s;

SELECT rsolp.pack_id from rp_sale_order_line_pack AS rsolp, sale_order_line AS sol
WHERE rsolp.sale_line_id = sol.id
AND sol.id in %s;  

5 个答案:

答案 0 :(得分:2)

如果要合并来自两个不同查询的两个结果,可以使用UNION语法:

SELECT st.tracking_id FROM sale_order_line_tracking AS st, sale_order_line AS sol 
WHERE st.order_line_id = sol.id
AND sol.id in %s
UNION
SELECT rsolp.pack_id from rp_sale_order_line_pack AS rsolp, sale_order_line AS sol
WHERE rsolp.sale_line_id = sol.id
AND sol.id in %s;

这将返回一个结果表,但您的查询彼此之间太相似,因此最好使用JOIN

答案 1 :(得分:1)

您可以尝试使用JOIN

SELECT st.tracking_id,rsolp.pack_id
FROM sale_order_line_tracking AS st join sale_order_line AS sol 
on st.order_line_id = sol.id join rp_sale_order_line_pack AS rsolp
on rsolp.sale_line_id = sol.id
AND sol.id in %s;

答案 2 :(得分:1)

以下可以是联接查询之一。但是现在取决于您是要相应的LEFT还是RIGHT连接,您可以修改查询。

您还可以更改先使用跟踪表还是先使用销售订单表的顺序,以使其与您的业务案例相关。

SELECT st.tracking_id,rsolp.pack_id
    FROM sale_order_line_tracking AS st Join sale_order_line AS sol 
        on st.order_line_id = sol.id 
        Join rp_sale_order_line_pack AS rsolp on rsolp.sale_line_id = sol.id
WHERE sol.id in %s;

答案 3 :(得分:1)

进行两次LEFT JOIN

SELECT sol.*, st.tracking_id, rsolp.pack_id
FROM sale_order_line AS sol 
LEFT JOIN sale_order_line_tracking AS st
    ON st.order_line_id = sol.id
LEFT JOIN rp_sale_order_line_pack AS rsolp
    ON rsolp.sale_line_id = sol.id
WHERE sol.id in %s;

答案 4 :(得分:1)

您需要以这种方式运行:

SELECT st.tracking_id FROM sale_order_line_tracking AS st, sale_order_line AS sol 
WHERE st.order_line_id = sol.id
AND sol.id in %s
UNION
SELECT rsolp.pack_id from rp_sale_order_line_pack AS rsolp, sale_order_line AS sol
WHERE rsolp.sale_line_id = sol.id
AND sol.id in %s;