SQL使用JOIN嵌套SELECT

时间:2014-09-08 16:30:12

标签: sql sql-server

我在一次查询中整天都没有成功浪费, SOS 我需要帮助:)给定的 @CustomerId ,我需要查询链接的所有产品顾客卖家可以卖,但之前卖给他,佣金表是卖家可以卖的产品的标志

enter image description here

提前致谢

3 个答案:

答案 0 :(得分:2)

SELECT sellableProduct
FROM (SELECT Comissions.ProductId AS sellableProduct, Sellers.SellerId AS sellableSeller FROM Comissions INNER JOIN Sellers ON Comissions.SellerId=Sellers.SellerId INNER JOIN Customers ON Sellers.SellerId=Customers.SellerId WHERE Customers.CustomerId = @customerid) AS tblSellable
LEFT JOIN (SELECT Sales.ProductId AS soldProduct, Customers.SellerId as soldSeller FROM Customers INNER JOIN Sales ON Customers.CustomerId=Sales.CustomerId WHERE Customers.CustomerId = @customerid) AS tblSold
ON tblSellable.sellableProduct=tblSold.soldProduct AND tblSellable.sellableSeller=tblSold.soldSeller
WHERE tblSold.soldProduct IS NULL

这样可以避免耗时的IN语句

如果客户只能拥有一个卖家,那么您可以省略卖家链接:

SELECT sellableProduct
FROM (SELECT Comissions.ProductId AS sellableProduct FROM Comissions INNER JOIN Sellers ON Comissions.SellerId=Sellers.SellerId INNER JOIN Customers ON Sellers.SellerId=Customers.SellerId WHERE Customers.CustomerId = @customerid) AS tblSellable
LEFT JOIN (SELECT Sales.ProductId AS soldProduct FROM Sales WHERE Sales.CustomerId = @customerid) AS tblSold
ON tblSellable.sellableProduct=tblSold.soldProduct
WHERE tblSold.soldProduct IS NULL

答案 1 :(得分:1)

基本上,您正在寻找具有commissions但不在sales的记录的产品。使用:id表示特定ID:

SELECT *
FROM   products
WHERE  productid IN (SELECT productid
                     FROM   commissions
                     WHERE  sellerid = :id) AND
       productid NOT IN (SELECT productid
                         FROM   sales
                         JOIN   customers ON sales.customerid = cusomers.customerid
                         WHERE  sellerid = :id)

答案 2 :(得分:0)

这会有用吗?

SELECT sell.*, prod.* FROM 
Sellers sell
INNER JOIN Customers cust ON cust.SellerId = sell.SellerId
LEFT JOIN Commissions comm ON sell.SellerId = comm.SellerId
LEFT JOIN Products prod ON prod.ProductId = comm.ProductId
WHERE prod.ProductId NOT IN (
SELECT ProductId
FROM Products p INNER JOIN 
Sales s ON s.ProductId = p.ProductId
WHERE s.CustomerId = @CustomerId

它从佣金获得所有卖家和相应的产品,其中产品ID与客户的任何销售无关