dougong1031 2017-11-13 05:14
浏览 73
已采纳

合并多行然后离开join-php mysql

I have two tables: invoices and sales. These are simplified version of them:

Invoices:

InvoiceNo  |  ProductNo  |  QtyIn   
-----------------------------------
F01        |  00001      |  20
F01        |  00002      |  50
F01        |  00003      |  15
F02        |  00002      |  10

Sales:

Date    |  ProductNo  |  QtyOut   
---------------------------------
3/2/17  |  00002      |  12
3/3/17  |  00002      |  8
3/4/17  |  00003      |  10

What I'm trying to do is to make a stock summary table, which looks like this:

ProductNo  |  QtyIn  |  QtyOut  |  Stock
-------------------------------------------
00001      |  20     |  0       |  20
00002      |  60     |  20      |  40
00003      |  15     |  10      |  5

To make that stock table, as far as I can think is:

  • Make another database for invoice where same product will be merge and it's quantity will be sum up.
  • Make something like the first one for sales.
  • Then make a join table for both of them.

By this way, I will end up having 5 tables. Is there any simpler way to do this? Thanks.

  • 写回答

2条回答 默认 最新

  • douyong1908 2017-11-13 05:28
    关注

    If you apply a filer on Invoices and Sales (e.g. for a date range) either filtered result could have products not referenced in the other. Hence a single outer join does not cover all possible conditions. As there is no "full outer join" in MySQL a simple method to overcome this is to union all source rows then group that:

    select ProductNo, sum(QtyIn) QtyIn, sum(QtyOut) QtyOut, sum(QtyIn) - sum(QtyOut) Stock
    from (
          select ProductNo, QtyIn, 0 as QtyOut
          from invoices 
            # where datecol >= `2017-01-01`
          union all
          select ProductNo, 0 as QtyIn, QtyOut
          from Sales
            # where datecol >= `2017-01-01`
         ) u
    group by ProductNo
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b