我有三个表:orders,purchase_order和sale_order。表顺序有两列:外键order_id和order_numb。 Order_id是purchase_order或sale_order的id,order_numb只是说明它的顺序。
order_numb = 1它是purchase_order order_numb = 2是sale_order
所以我需要从表顺序中进行选择,并且对于每一行检查它是否具有order_numb = 1或order_numb = 2,并且基于该结果,根据他们的id从buy_order或sale_order中选择。
我可以使用两个查询,但我想在一个查询中完成。
ORDER
| order_id | action_numb |
--------------------------
| 51 | 1 |
--------------------------
| 40 | 2 |
--------------------------
| 41 | 2 |
--------------------------
| 52 | 1 |
PURCHASE_ORDER
| id | other_columns |
----------------------
| 51 | something |
----------------------
| 52 | something |
SALE_ORDER
| id | other_columns |
----------------------
| 40 | something |
----------------------
| 41 | something |
----------------------
答案 0 :(得分:1)
SELECT o.*
, CASE
WHEN so.id is null THEN po.other_columns
WHEN po.id is null THEN so.other_columns
END other_columns
FROM orders o
LEFT JOIN purchase_order po
ON po.id = o.order_id
AND o.order_numb = 1
LEFT JOIN sale_order so
ON so.id = o.order_id
AND o.order_numb = 2
答案 1 :(得分:1)
假设您从两个表中选择相同的列,您可以使用UNION来完成任务。
SELECT o.id,<other-columns>
FROM order o INNER JOIN purchase_order po
ON o.id = po.id
WHERE o.action_numb = 1
UNION
SELECT o.id,<other-columns>
FROM order o INNER JOIN sale_order so
ON o.id = so.id
WHERE o.action_numb = 2