Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
mysql 3在一个数据库中查询2个表_Mysql_Join - Fatal编程技术网

mysql 3在一个数据库中查询2个表

mysql 3在一个数据库中查询2个表,mysql,join,Mysql,Join,我有两个表需要查询 **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

我有两个表需要查询

**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相加,并给出每个作业ID的sumadd sumrem总数,包括剩余的作业信息

jobid | description | someinfo | amountadd | amountrem | totaladdrem
1     | foo         | bar      | 108       | 65        | 43
2     | fuu         | buu      | 42        | 0         | 42
我用select*from select…做了一个四重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将允许您使用名为hidden columns的特性,只需执行group by j.jobid。我认为这是一个坏习惯,除了在少数情况下,因此这会按jobs表中的所有列进行聚合

条件聚合是通过在sum语句中放入一个条件来完成的