1

我有 3 张桌子products和.stockpurchases

Puchases有一个primary keypurchaseID

我的products表有一个primary keyofproductID然后列,其中包含有关产品的详细信息。

我的stock桌子上有一个ofprimary key和另一个of 。framenumberforeign keyproductIDforiegn keypurchaseID

并非所有产品都有库存。

我想和库存表在join最后有一行,它计算列中空值的数量,它代表我有多少库存。prodcutsproductIDpurchaseID

我已经尝试了很多,queries但似乎总是想出stock表格中的条目总数或subqueries没有正确加入。

我尝试过的一些事情

SELECT * , COUNT( * ) AS Count
FROM Products
LEFT JOIN Stock ON Products.productID = Stock.productID
WHERE Stock.OrderID IS NULL AND Stock.framenumber IS NOT NULL
GROUP BY Products.productID

只是给我按productID分组的所有库存对象的计数,而不是加入所有产品

架构

CREATE TABLE BikeStock (

FrameNumber VARCHAR(10) PRIMARY KEY,
BikeCode VARCHAR(40),
OrderID INT,
FOREIGN KEY (BikeCode) REFERENCES Bike(BikeCode),
FOREIGN KEY (OrderID) REFERENCES Purchase(OrderID)
);

CREATE TABLE Bike (

BikeCode VARCHAR (40) PRIMARY KEY,
Manufacturer VARCHAR (30),
Model VARCHAR (30),
SubType VARCHAR (30),
Year SMALLINT,
FrameMaterial VARCHAR (20),
Description TEXT,
Gender VARCHAR (6),
Type VARCHAR (20),
Price DECIMAL (11,2)
);


CREATE TABLE Purchase (

DateOfPurchase DATETIME,
OrderID INT NOT NULL AUTO_INCREMENT, 
PRIMARY KEY(OrderID),
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID)

);
4

1 回答 1

2
SELECT Products.productID , SUM( 
case 
   when  (Stock.OrderID IS NULL AND Stock.framenumber IS NOT NULL) 
      then 1 
      else 0 
end case
) AS Count
FROM Products
LEFT JOIN Stock ON Products.productID = Stock.productID
GROUP BY Products.productID
于 2012-12-12T13:25:01.993 回答