从带有IF语句的JOIN获取行结果

时间:2018-08-14 04:56:43

标签: mysql

我有“交易”表:

id user amount plan_id
1   1     11      1       
2   1     9       2
3   1     10      2
4   2     10      3
5   1     7       4
6   1     5       4
7   1     6       5
8   3     3       8
7   1     7       5

和“计划”表:

plan_id type status
  1      0     0
  2      1     1
  3      1     0
  4      1     0
  5      0     1

我需要获取“交易”中给出的每个plan_id金额的总和。但是,如果对于特定的plan_id,“计划”表中的类型为“ 0”且状态为“ 1”,则仅在这种情况下,总和将返回“ 0”。

这就是返回的内容:

plan_id earnings
   1      11     
   2      19
   4      12
   5       0  // it should be 13, but because type=0 and status=1, sum returns 0

到目前为止,我有:

SELECT t.plan_id, 
SUM( IF( p.type = 0 and p.status = 1 , 0, t.amount ) ) as earnings
FROM transactions as t
WHERE t.user = 1
INNER JOIN plans as p ON t.plan_id=p.plan_id;
GROUP BY t.plan_id  

但是由于某种原因它不起作用。我的想法不多了。

请帮助。谢谢

2 个答案:

答案 0 :(得分:1)

由于在JOIN之间使用了WHERE子句,因此您的SQL查询存在语法错误。

如果我正确,我已经修改了您的SQL查询并找到了预期的结果。

SELECT t.plan_id, 
       SUM(IF(p.TYPE = 0 
              AND p.status = 1, 0, t.amount)) AS earnings 
FROM   transactions AS t 
       inner join plans AS p 
               ON t.plan_id = p.plan_id 
WHERE  t.USER = 1 
GROUP  BY t.plan_id; 

答案 1 :(得分:-1)

SELECT t.plan_id, sum(t.amount) as total 
FROM plans as p 
inner join transactions as t on (p.plan_id = t.plan_id) 
where t.user = 1 
group by t.plan_id

我想您可以使用上面的查询简单地实现