1

我正在尝试将来自两组不同表的结果组合成一个结果。到目前为止,这是我的查询:

SELECT * 
FROM ( SELECT product_table1.product_id as product_id, sum(product_table1.qty) as quantity, sum(product_table1.paid) as amount  
FROM product_table1
LEFT JOIN table2 ON table2.id = product_table1.table2_id
WHERE product_table1.product_id IN ( SELECT id FROM products_table WHERE active = 'yes' )
AND table2.active = 'yes'
GROUP BY product_id

UNION 

SELECT product_table2.product_id as product_id, sum(product_table2.qty) as quantity, sum(product_table2.paid) as amount 
FROM product_table2
LEFT JOIN table3 ON table3.id = product_table2.table3_id
WHERE product_table2.product_id IN ( SELECT id FROM products_table WHERE active = 'yes' )
AND table3.active = 'yes'
GROUP BY product_id

) AS product_sales

以下是数据返回的方式:

product_id | quantity | amount
1            100        200
2            200        300
3            300        600
1            500        700
4            200        200

我试图弄清楚如何最好地采用这两组数字(每组具有相同数量的列和数据类型),并将它们组合成一组结果,而不必将 php 带入其中。这可能吗?

我找到了其他一些解决方案,但不确定它们是否符合我想要做的。我认为我需要的另一种解决方案的示例,但不确定..

4

2 回答 2

5

GROUP BY在你的外部使用,SELECTUNION ALL不是UNION

SELECT product_id,  
       SUM(quantity) as quantity,
       SUM(amount) as amount
  FROM ( 
    SELECT product_table1.product_id as product_id, 
           SUM(product_table1.qty) as quantity, 
           SUM(product_table1.paid) as amount  
      FROM product_table1
      LEFT JOIN table2 ON table2.id = product_table1.table2_id
     WHERE product_table1.product_id IN ( SELECT id FROM products_table WHERE active = 'yes' )
       AND table2.active = 'yes'
     GROUP BY product_id
     UNION ALL
    SELECT product_table2.product_id as product_id, 
           SUM(product_table2.qty) as quantity, 
           SUM(product_table2.paid) as amount 
      FROM product_table2
      LEFT JOIN table3 ON table3.id = product_table2.table3_id
     WHERE product_table2.product_id IN ( SELECT id FROM products_table WHERE active = 'yes' )
       AND table3.active = 'yes'
     GROUP BY product_idc) AS product_sales
 GROUP BY product_id
于 2013-04-03T16:09:16.810 回答
3

只需进行聚合:

select product_id, sum(quantity) as quantity, sum(amount) as amount
from (<your query here>)
group by product_id

我要补充一点,您可能想要使用union all而不是union. 如果两个源返回完全相同的值,您可能希望保留两者(union删除重复项)。

于 2013-04-03T16:04:12.960 回答