MySQL SELECT运行多次

时间:2016-10-26 12:10:56

标签: mysql if-statement select sum left-join

当我运行我的SELECT语句时,它运行IFNULL部分三次和SUM CASE部分两次。我知道这与声明中的太多LEFT JOIN有关。但无法找到问题的解决方案。

很难解释这个问题所以我已经包含了sqlfiddle链接。

SQLFIDDLE

SELECT 
IFNULL(SUM(d.quantity),0) as dispatch, 
SUM(CASE WHEN t.valuefor='alpha' THEN t.quantity ELSE 0 END) as alpha,
SUM(CASE WHEN t.valuefor='beta' THEN t.quantity ELSE 0 END) as beta 
FROM conversion as c 
LEFT JOIN sale as s ON s.conversionid = c.id 
LEFT JOIN dispatch as d ON d.saleid = s.id 
LEFT JOIN test as t ON t.conversionid = c.id

当前输出

dispatch    alpha   beta
1800        1400    80

期望输出

dispatch    alpha   beta
600         700     40

2 个答案:

答案 0 :(得分:2)

您需要将调度值与测试值相加 - 这样的事情可能会给出您想要的答案:

Select A.dispatch,
SUM(CASE WHEN t.valuefor='alpha' THEN t.quantity ELSE 0 END) as alpha,
SUM(CASE WHEN t.valuefor='beta' THEN t.quantity ELSE 0 END) as beta 
FROM(
  SELECT sum(quantity) AS dispatch, c.id
  FROM conversion as c 
  LEFT JOIN sale as s ON s.conversionid = c.id 
  LEFT JOIN dispatch as d ON d.saleid = s.id
  GROUP BY d.saleid) A
LEFT JOIN test as t ON t.conversionid = A.id
group by A.id;

内部子查询总计调度值,然后加入测试数量。

答案 1 :(得分:1)

尝试这种方式:

SELECT 
  IFNULL(SUM(d.quantity),0) as dispatch, 
  SUM(t.alpha) as alpha,
  SUM(t.beta) as beta 
 FROM conversion as c 
 LEFT JOIN sale as s ON s.conversionid = c.id 
 LEFT JOIN (
   SELECT saleid, SUM(quantity) AS quantity
   FROM dispatch 
   GROUP BY saleid) as d ON d.saleid = s.id 
 LEFT JOIN (
   SELECT conversionid, 
          SUM(CASE WHEN valuefor='alpha' THEN quantity ELSE 0 END) as alpha,
          SUM(CASE WHEN valuefor='beta' THEN quantity ELSE 0 END) as beta 
   FROM test 
   GROUP BY conversionid) as t ON t.conversionid = c.id

上述查询在dispatch操作中这些表之前对表testLEFT JOIN执行聚合。

Demo here