2013-08-21 35 views
0

我有2个表,我需要查询MySQL的3个查询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 

的结果应该是使库存化“添加”和“REM”的总和,并给出一个总的为每个jobid添加sum(add)-sum(rem),包括其余的作业信息。

jobid | description | someinfo | amountadd | amountrem | totaladdrem 
1  | foo   | bar  | 108  | 65  | 43 
2  | fuu   | buu  | 42  | 0   | 42 

我做了一个四选择语句与选择*从(选择....)不使用连接或其他很酷的东西。这是非常缓慢的。我对mysql很新。

我很高兴能就如何解决这个问题的想法。 由于事先

回答

2

这是一个需要加入和有条件的聚集查询:

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将允许您只使用名为“hidden columns”的功能执行group by j.jobid。我认为这是一个坏习惯(除了少数情况外),所以这将聚合到作业表中的所有列。

通过在sum()语句中添加条件来完成条件聚合。

+0

非常感谢。这解决了我的整个问题。 :) – swish