启用所有条目的SQL查询

时间:2012-02-11 18:06:57

标签: sql ms-access

我正在开发一个数据库,我有一张桌子(比方说材料)。我有第二张表让我保存我买的材料让我们说buy_elements。例如

MatID:Mat1>数量:3

MatID:Mat2>数量:4

MatID:Mat5>数量:2

MatID:Mat1>量:5

当我想看到我用查询购买的材料时

SELECT materials.id, 
       materials.name, 
       Sum(purchase_elements.quantity) AS QUANTITY
 FROM materials 
   INNER JOIN purchase_elements 
 ON materials.id= purchase_elements.id
 GROUP BY materials.id, 
          materials.name;

显示

Id/name/QUANTITY
1 Mat1  8
2 Mat2  4   
5 Mat5  2

查询是否有任何方式不仅向我展示我购买的材料,还包括所有这些材料

Id/name/QUANTITY
1 Mat1  8
2 Mat2  4   
3 Mat3
4 Mat4
3 Mat5  2

2 个答案:

答案 0 :(得分:1)

您需要执行LEFT OUTER JOIN,因为INNER JOIN会将行限制为仅购买的材料,并过滤不属于purchase_elements表的材料。您需要按如下方式修改查询:

SELECT M.id, M.name, SUM(PE.quantity) AS QUANTITY
FROM materials AS M
     LEFT OUTER JOIN purchase_elements AS PE ON M.id= PE.MatID
GROUP BY M.id, M.name;

答案 1 :(得分:0)

使用left join

SELECT materials.id, 
   materials.name, 
   Sum(purchase_elements.quantity) AS QUANTITY
FROM materials 
 LEFT JOIN purchase_elements 
ON materials.id= purchase_elements.[Υλικά IID]
GROUP BY materials.id, 
      materials.name;