我正在尝试将来自两组不同表的结果合并为一个结果。这是我到目前为止的查询:
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带入其中。这可能吗?
我找到了其他一些解决方案,但我不确定它们是否符合我的要求。我认为Example of another solution是我需要的,但不确定......
答案 0 :(得分:5)
在外部GROUP BY
和SELECT
代替UNION 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
答案 1 :(得分:3)
只需进行汇总:
select product_id, sum(quantity) as quantity, sum(amount) as amount
from (<your query here>)
group by product_id
我想补充一点,您可能希望使用union all
代替union
。如果两个源返回完全相同的值,您可能希望保留两者(union
删除重复项。)