本质上,我有两个表:
表 A
aId|isOne|bId
---+-----+---
1 |1 |2
2 |0 |2
3 |1 |1
表B
bId|one|two
---+---+---
1 |5 |13
2 |3 |11
表A 引用表B 并指定是否需要one
或two
的数据。我需要做的是对给定 bId
的值求和,因此对这些表的查询的预期结果将是:
bId|value
---+-----
2 |14
1 |5
目前我的查询具有以下形式:
select bId,
coalesce(if(bId = 0, null,
sum(if(isOne = 0,
(select two from tableB where tableB.bId = bId),
(select one from tableB where tableB.bId = bId)))) as value
from (select bId, isOne, one, two from tableA
join tableB on tableA.bId = tableB.bId) as tableRes;
请注意,这是一个较大查询的相关部分并使用较大的表,其中合并和第一个 if 语句确实可以使用。
虽然上面的查询发生了错误(
Error Code: 1242. Subquery returns more than 1 row)
这被认为来自 sum()
中的 if 语句。我已尝试应用 group by
,因为我认为我需要将 bId = 2
值结果分组在一起,但无法合法放置或放置它合法地在查询中并让它真正阻止子查询返回多个结果。任何指导或帮助修复错误将不胜感激,也可能很高兴知道如上所述,这是查询的精简版本,因此如果认为问题不在已显示的内容中,可以添加更多内容,但我对上述版本中的错误很有信心。
最佳答案
我会简单地内部连接 2 个表并在 sum() 中使用 case 语句来求和正确的值:
select tableA.bId, sum(case when isOne=0 then two when isOne=1 then one else 0 end) as val
from tableA
inner join tableB on tableA.bId = tableB.bId
group by tableA.bId ;
关于mysql - 将 Group By 应用于 If 语句结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36190633/