MYSQL选择连接多个表和SUM

时间:2016-09-01 00:24:33

标签: mysql join sum left-join inner-join

我有三张桌子

1.master

id_trans_in barcode qty time_trans 
1           567     1   2016-04-01 10:15:09
2           234     2   2016-04-01 14:15:09
3           345     5   2016-04-01 20:15:09

2。 trans_in

id_trans_out barcode qty time_trans 
1           123     3   2016-04-01 09:15:09
2           234     5   2016-04-01 08:15:09

3。 trans_out

id_master barcode name last_stock in out
1         123     abc  15         0   3
2         234     bcd  10         2   5
3         345     cde  7          5   0
4         456     def  11         0   0
5         567     efg  20         1   0

我必须构建一个查询来提供结果

select
    a.id_master, a.barcode, a.name,
    COALESCE(SUM(b.qty),'0')
from
    master a
inner join trans_in b
on a.barcode = b.barcode
where
    date(b.time_trans) = '2016-04-01'   
group by a.barcode

我只是尝试简单的查询

id_master barcode name COALESCE(SUM(b.qty),'0')
5         567     efg  1
2         234     bcd  2
3         345     cde  5

结果是

infinite: true
variableWidth: true

我不知道如何通过time_trans组合master,trans_in和trans_out的完整列表(如果为null然后为0),我已经尝试使用左连接,其中三个内连接但结果让我头晕..来自SUM的结果来自现场的不仅仅是数量,我真的不知道为什么。

2 个答案:

答案 0 :(得分:0)

如果每个日期有多个条目

,你可以加入一些派生表
    SELECT  a.id_master ,
        a.barcode ,
        a.name ,
        a.last_stock ,
        COALESCE(b.`IN`, 0) AS `IN`,
        COALESCE(c.`OUT`, 0) AS `OUT`
FROM    master a
        LEFT JOIN (SELECT barcode, SUM(qty) as `IN` 
                     FROM trans_in 
                     WHERE date(time_trans) = '2016-04-01' 
                     GROUP BY barcode ) b ON a.barcode = b.barcode
        LEFT JOIN (SELECT barcode, SUM(qty) as `OUT`
                     FROM trans_out 
                     WHERE date(time_trans) = '2016-04-01' 
                     GROUP BY barcode ) c  ON a.barcode = c.barcode;

答案 1 :(得分:0)

E.g:

SELECT m.* 
     , COALESCE(SUM(CASE WHEN type = 'trans_in' THEN qty END),0) `in`
     , COALESCE(SUM(CASE WHEN type = 'trans_out' THEN qty END),0) `out` 
  FROM master m 
  LEFT 
  JOIN 
     ( SELECT 'trans_in' type
            , id_trans_in id_trans
            , barcode
            , qty
            , time_trans 
         FROM trans_in 
        WHERE time_trans BETWEEN '2016-04-01 00:00:00' AND '2016-04-01 23:23:59' 
        UNION ALL
       SELECT 'trans_out'
            , id_trans_out
            , barcode
            , qty,time_trans 
         FROM trans_out
        WHERE time_trans BETWEEN '2016-04-01 00:00:00' AND '2016-04-01 23:23:59' 
     ) x 
    ON x.barcode = m.barcode
 GROUP 
    BY m.id_master
 ORDER
    BY id_master;

考虑将交易存储在单个表中。它将简化并加速这一过程。另外,我在time_trans上假设了一个INDEX,并相应地构建了一个范围查询。