我有 2 个表需要查询
**tbl_jobs**
jobid | description | someinfo
1 foo bar
2 fuu buu
**tbl_invlog**
idinv | jobid | type | ammount
1 1 add 100
2 1 rem 50
3 1 rem 15
4 1 add 8
5 2 add 42
结果应该是对库存“add”和“rem”进行求和,并给出每个 jobid 的总和(add)-sum(rem),包括其余的工作信息。
jobid | description | someinfo | amountadd | amountrem | totaladdrem
1 | foo | bar | 108 | 65 | 43
2 | fuu | buu | 42 | 0 | 42
我用 select * from (select .... ) 做了一个四重选择语句,而不使用连接或其他很酷的东西。这非常慢。我对 mysql 很陌生。
我很高兴知道如何解决这个问题。 提前致谢
最佳答案
这是一个需要连接和条件聚合的查询:
select j.jobid, j.description, j.someinfo,
sum(case when il."type" = 'add' then amount else 0 end) as AmountAdd,
sum(case when il."type" = 'rem' then amount else 0 end) as AmountRem,
(sum(case when il."type" = 'add' then amount else 0 end) -
sum(case when il."type" = 'rem' then amount else 0 end)
) as totaladdrem
from tbl_jobs j left outer join
tbl_invlog il
on j.jobid = il.jobid
group by j.jobid, j.description, j.someinfo;
注意一些事情。首先,这些表具有在 from
子句中定义的表别名。这允许您说出列来自哪个表。其次,表别名始终用于查询中的所有列。
MySQL 允许您使用名为“隐藏列”的功能来进行group by j.jobid
。我认为这是一个坏习惯(除了少数情况),因此这是通过 jobs 表中的所有列进行聚合的。
条件聚合是通过在 sum()
语句中添加条件来完成的。
关于mysql 3个查询合二为一的2个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18356424/