我正在尝试将来自两组不同表的结果组合成一个结果。到目前为止,这是我的查询:
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 带入其中。这可能吗?
我找到了其他一些解决方案,但不确定它们是否符合我想要做的。我认为我需要的另一种解决方案的示例,但不确定..