使用group by的复杂MySQL查询

时间:2012-04-16 18:35:42

标签: mysql

假设我有两张桌子

Table1:
product_id, design1, design2
1              A        C
2              B        A

Table2:
product_id, value
1             10
2             10

现在我想为所有产品的特定设计总结所有价值。

SELECT designA, SUM(value) FROM ( 
 SELECT b.design1 AS designA, SUM(value) AS value FROM table2 AS a LEFT JOIN table1 AS b ON a.product_id = b.product_id GROUP BY b.design1) AS T GROUP BY designA

It gives me this:
designA SUM(value)
  A           10
  B           10

现在的问题是,如果用户在table1中指定了design2,那么design1的值将自动添加到design2中。如果design2不存在design1列,那么它将是一个新的结果行:

结果如下:

designA SUM(value)
  A            20
  B            10
  C            10

2 个答案:

答案 0 :(得分:1)

select y.designA, sum(value) from 

(select  a.design1 as designA, value from
Table1 as a
inner join Table2 as b
on
a.product_id = b.product_id

union all

select a.design2 as designA, value from
Table1 as a
inner join Table2 as b
on
a.product_id = b.product_id) as y 
group by y.designA

似乎适用于您的测试数据,而不是尝试其他配置,但如果您了解它正在做什么,您应该能够调整它。

答案 1 :(得分:0)

基于design2的比赛中的UNION:

SELECT designA, SUM(value) FROM ( 
 SELECT b.design1 AS designA, SUM(value) AS value FROM table2 AS a LEFT JOIN table1 AS b ON a.product_id = b.product_id GROUP BY b.design1
UNION
 SELECT b.design2 AS designA, SUM(value) AS value FROM table2 AS a LEFT JOIN table1 AS b ON a.product_id = b.product_id GROUP BY b.design2
) AS T GROUP BY designA