Sql server查询连接两个表以获得所需的结果集

时间:2016-05-24 11:35:47

标签: sql sql-server sql-server-2008

我有两个表客户商品可用位置我需要获取客户商品中所有商品都可用的位置。

客户-项

ItemID    ItemName
   1        item1      
   2        item2 
   3        item3      

可用-地点

LocationID    ItemID      AvailableForPickup
   20           1             1
   20           2             1
   20           3             0
   21           1             1
   21           2             1
   21           3             1

简单的内连接,例如

 SELECT * FROM Customer-items
 INNER JOIN Available-locations
 ON Customer-items.ItemID = Available-locations.ItemsID AND AvailableForPicup = 1

这将从LocationID 20的Available-locations中排除第3项,但返回locationID 20的其他两个项目以及位置21的所有项目。

我需要获得结果集;如果任何项目不可用,则排除所有项目的位置。

可用-locations_CustomerItems

LocationID    ItemID      AvailableForPickup
   21           1             1
   21           2             1
   21           3             1

5 个答案:

答案 0 :(得分:0)

SELECT * FROM Customer-items
INNER JOIN Available-locations
ON Customer-items.ItemID = Available-locations.ItemsID AND locationId
NOT IN (select locationID FROM Available-locations WHERE AvailableForPicup = 0)

答案 1 :(得分:0)

SELECT B.ITEMID
    ,B.LOCATIONID
    ,B.AVAILABLEFORPICKUP
FROM #A A
RIGHT JOIN #B B ON A.ITEMID = B.ITEMID
WHERE B.AVAILABLEFORPICKUP= 1

答案 2 :(得分:0)

您可以在以下内容中使用NOT IN

 SELECT l.* 
 FROM [Customer-items] AS i 
 INNER JOIN [Available-locations] AS l ON i.ItemID = l.ItemID
 WHERE l.LocationID NOT IN (SELECT LocationID FROM [Available-locations] WHERE AvailableForPicup = 0) 

请注意,-在表名中不可用。您必须在[]等表名上使用括号[customer-items]。还要在表上使用别名,以使其更具可读性。

<强>输出

LocationId  ItemId  AvailableForPickup
21          1       1
21          2       1
21          3       1

答案 3 :(得分:0)

select * from Customer-items
join Available-locations
on Customer-items.ItemID = Available-locations.ItemsID
where Available-locations.LocationID in 
(select LocationID from Available-locations where AvailableForPickup = 1)

答案 4 :(得分:0)

请使用以下代码。它在SQL Server 2012中运行良好。

DECLARE @Customer_Items TABLE (ItemsID int,ItemName VARCHAR(10))
DECLARE @Available_Locations TABLE (LocationID int,ItemsID int,AvailableForPickup int)
INSERT INTO @Customer_Items (ItemsID,ItemName)
VALUES
(1,'item1'),
(2,'item2'),
(3,'item3')
INSERT @Available_Locations
(LocationID,ItemsID,    AvailableForPickup)
VALUES
(20,1,1),
(20,2,1),
(20,3,0),
(21,1,1),
(21,2,1),
(21,3,1)

SELECT LocationID,al.ItemsID,AvailableForPickup FROM @Customer_Items ci
 INNER JOIN @Available_Locations al
 ON ci.ItemsID = al.ItemsID AND al.AvailableForPickup = 1
 WHERE al.LocationID NOT IN (SELECT al2.LocationID FROM @Available_Locations al2 WHERE al2.AvailableForPickup =0)