0

假设我有 Product 和 RelatedProduct 表,

Product
------
ID
Name

RelatedProduct
--------------
ID
ProductID
RelatedProductID
RelatedProductName

现在我有一个@ProductID 参数。我需要获取尚未添加到 RelatedProduct 表中的所有产品。所以,如果我有

Product
-----------
ID     Name
 1      A1
 2      A2
 3      A3
 4      A4


RelatedProduct
-----------------------------------------
ID     Name   ProductID    RelatedProductID
 1      B1       2             1
 2      B2       4             3
 3      B3       2             4

如果@ProductID =1,那么我需要产品的 2、3、4。如果@ProductID = 2,那么我需要 Product 的 3。如果 @ProductID = 4,那么我需要 Product 的 1,2。

4

1 回答 1

1
select *
from    Product
where   id not in
  (select RelatedProductID
   from   RelatedProduct
   where  productID = @productID)

NOTE: if product 1 is related to product 2, is product 2 then also related to product 1? Your examples explicitly say no, but often this kind of relationship is bi-directional.

于 2013-03-27T11:42:35.343 回答