SQL加入两个具有不同列数的查询

时间:2015-05-19 14:49:58

标签: sql database join

首次查询 :(我已添加了计数(*)以进行简化)

select count(*) from Sales_order_line sol
where
sol.grant_type_id is null
AND
 sol.quantity  - NVL ((SELECT SUM (salesorder15_.assigned_quantity) FROM license_link_sales_ord_ln salesorder15_  
 WHERE salesorder15_.sales_order_line_id = sol.ID),0) > 0;

第二次查询 :(我已添加了计数(*)以进行简化)

select count(*) from Sales_order_line sol
INNER JOIN license_link_sales_ord_ln sola
ON sol.id=sola.sales_order_line_id
where
sol.grant_type_id is null;

第一个查询返回 56119 ,第二个返回 362260 。我想结合使用(56119 +362260)作为结果的查询。

2 个答案:

答案 0 :(得分:2)

要将查询与不同数量的列结合起来,您需要使用null填充不相同的列(在两个查询中不匹配),如下所示:

SELECT columnA, columnB, columnC, columnD, columnE
FROM Sales_order_line s
WHERE s.grant_type_id IS NULL
AND s.quantity  - NVL ((SELECT SUM (so.assigned_quantity) 
                        FROM license_link_sales_ord_ln so
                        WHERE so.sales_order_line_id = s.ID),0) > 0
UNION ALL
SELECT columnA, columnB, columnC, null, null
FROM Sales_order_line s
INNER JOIN license_link_sales_ord_ln l ON s.id = l.sales_order_line_id
WHERE s.grant_type_id IS NULL;

答案 1 :(得分:0)

使用UNION ALL

SELECT count(*) 
FROM Sales_order_line s
WHERE s.grant_type_id IS NULL
AND s.quantity  - NVL ((SELECT SUM (so.assigned_quantity) 
                        FROM license_link_sales_ord_ln so
                        WHERE so.sales_order_line_id = s.ID),0) > 0
UNION ALL
SELECT count(*)
FROM Sales_order_line s
INNER JOIN license_link_sales_ord_ln l ON s.id = l.sales_order_line_id
WHERE s.grant_type_id IS NULL;