kly*_*e_g 1 mysql union left-join
我试图将来自两组不同表的结果合并为一个结果.这是我目前的查询:
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
Run Code Online (Sandbox Code Playgroud)
以下是数据的回传方式:
product_id | quantity | amount
1 100 200
2 200 300
3 300 600
1 500 700
4 200 200
Run Code Online (Sandbox Code Playgroud)
我试图找出如何最好地采取这两组数字(每个具有相同数量的列和数据类型),并将它们组合成一组结果,而无需将PHP带入其中.这可能吗?
我找到了一些其他的解决方案,但我不确定它们是否符合我的要求.我认为另一种解决方案的例子是我需要的,但不确定..
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2226 次 |
| 最近记录: |