我有一个接近我想要的SQL语句:
SELECT CustomerList.*, Sales.Sales, Sales.MonthYear
FROM (CustomerList INNER JOIN WhoBuysWhat ON CustomerList.CustomerID = WhoBuysWhat.CustomerID) LEFT JOIN Sales ON CustomerList.CustomerID = Sales.CustomerID
WHERE WhoBuysWhat.ProductID=2
ORDER BY CustomerList.CustomerName;
这使我能够购买某个产品系列的所有客户以及该产品系列的Sales表中的任何销售。但我想要的是添加另一个WHERE语句。我想第一个INNER JOIN给我所有购买productID 2的客户。然后我想要加入销售匹配sales.monthyear =#1/1/2015#的销售。所以我尝试了(以不同的方式):
SELECT CustomerList.*, Sales.Sales, Sales.MonthYear
FROM ((CustomerList INNER JOIN WhoBuysWhat ON CustomerList.CustomerID = WhoBuysWhat.CustomerID) WHERE WhoBuysWhat.ProductID=2) LEFT JOIN Sales ON CustomerList.CustomerID = Sales.CustomerID
WHERE Sales.MonthYear=#1/1/2015#
ORDER BY CustomerList.CustomerName;
这不起作用。如果我这样做:
WHERE WhoBuysWhat.ProductID=2 AND Sales.MonthYear=#1/1/2015#
OR
WHERE Sales.ProductID=2 AND Sales.MonthYear=#1/1/2015#
它只给我那个月有销售额的客户。我希望所有购买该产品线的客户和任意销售的GIVEN月份。这可能在1个SQL语句中吗?我是否需要在第一个连接表中使用AS?我找不到任何能帮到我的东西。
J_K_M_A_N
编辑: 如果以后有人关心或需要帮助,这是最终的工作SQL语句。
SELECT CustomerList.*, Sales.SalesID, Sales.Sales, WhoBuysWhat.EntryID, WhoBuysWhat.Active
FROM (CustomerList INNER JOIN WhoBuysWhat ON CustomerList.CustomerID = WhoBuysWhat.CustomerID)
LEFT JOIN Sales ON (CustomerList.CustomerID = Sales.CustomerID AND Sales.MonthYear=#1/1/2015# AND Sales.ProductID=2)
WHERE WhoBuysWhat.ProductID=2
ORDER BY WhoBuysWhat.Active, CustomerList.CustomerName
答案 0 :(得分:0)
当您使用LEFT OUTER JOIN
并且想要从 Right 表中过滤某些记录时,您需要将右表过滤器移至{{1}条件else ON
将隐式转换为LEFT OUTER JOIN
为了简短起见,INNER JOIN
条款拒绝 WHERE
行,NULL
为非匹配记录生成
LEFT OUTER JOIN
答案 1 :(得分:0)
我认为您可以使用子查询在MS Access中执行您想要的操作:
SELECT cl.*, s.sales, s.monthyear
FROM (customerlist as cl INNER JOIN
whobuyswhat as wbw
ON cl.customerid = wbw.customerid
) LEFT JOIN
(SELECT s.*
FROM sales as s
WHERE s.monthyear = #1/1/2015#
) as s
ON (cl.customerid = s.customerid
WHERE wbw.ProductID = 2
ORDER BY cl.customername;