MySQL COUNT项库存

时间:2014-05-07 13:55:31

标签: mysql sql

目前我有这些观点:

CREATE View InMaterial AS 
 Select Cat.descricao as Category, 
        Mar.descricao as Brand, 
        Mo.descricao as Model, 
        COUNT(Ent.n_serie) as Qty 
   From Categoria Cat, Marca Mar, Modelo Mo, Material Mat, Entrada Ent 
  Where Cat.id_categoria=Mo.categoria 
    AND Mar.id_marca = Mo.id_marca 
    AND Mo.id_modelo = Mat.id_modelo 
    AND Mat.n_serie = Ent.n_serie 
Group by Cat.descricao,Mar.descricao,Mo.descricao;

Create View OutMaterial As 
 Select Cat.descricao as Category, 
        Mar.descricao as Brand, 
        Mo.descricao as Model, 
        COUNT(Sai.n_serie) as Qty 
   From Categoria Cat, Marca Mar, Modelo Mo, Material Mat, Saida Sai 
  Where Cat.id_categoria=Mo.categoria 
    AND Mar.id_marca = Mo.id_marca 
    AND Mo.id_modelo = Mat.id_modelo 
    AND Mat.n_serie = Sai.n_serie 
 Group by Cat.descricao,Mar.descricao,Mo.descricao;

Create View Stocks AS 
 Select E.Categoria as Category, 
        E.Marca as Brand, 
        E.Modelo as Model, 
        E.Qty - S.Qty as Quantity 
   From InMaterial E, OutMaterial S 
  Where E.Brand=S.Brand 
    AND E.Model=S.Model 
    AND E.Category=S.Category 
 GROUP BY Category,Brand,Model;

这些观点的结果如下所示:

InMaterial

Category Brand     Model      Qty
 FF      JUNIPER   556655     2
 SFP     CISCO     2901       2

OutMaterial

Category Brand     Model      Qty
 FF      JUNIPER   556655     1

库存

Category Brand     Model      Qty
 FF      JUNIPER   556655     1

正如你所看到的,我已经发送了#34;""发送" 1 FF Juniper 556655离开仓库,所以我应该保留2个CISCO 500和1个Juniper 556655。

这些观点的目的是显示每个项目的数量(数量),但是当我运行库存选择时,2 SFP CISCO 500没有显示,但它们有库存。 / p>

我正在为这个问题寻找解决方案,因为我必须很快完成这个项目......

1 个答案:

答案 0 :(得分:1)

您应该将Stocks视图重新定义为LEFT JOIN。左连接从第一个表中获取所有列,而不管第二个表中的匹配。

这种行为在这种情况下是理想的,因为你不能拥有OutMaterial行,这些行以前不在InMaterial中(我假设)。

新视图定义:

Create View Stocks AS 
Select E.Categoria as Category, 
E.Marca as Brand, 
E.Modelo as Model, 
E.Qty - (coalesce(S.Qty,0)) as Quantity 
From InMaterial E
LEFT JOIN
OutMaterial S 
ON 
E.Brand=S.Brand AND 
E.Model=S.Model AND 
E.Category=S.Category 
GROUP BY Category,Brand,Model;

您会注意到我还重新定义了Quantity,合并部分将缺失值更改为零。