0

我创建了以下存储过程:

订单详细信息 -Id(int), OrderId(int), AnniID(int), Quantity(int), UnitCost(money)

周年纪念日 -AnniID (int), Title( varchar(50) )

AnniID 将成为连接 2 个表的外键。

当我执行存储过程时,尽管它实际上在数据库中有 1 个项目,但它什么也不返回。

代码有问题吗?还是我没有正确地进行内部连接?

ALTER PROCEDURE dbo.Selectpurchasedwithproducts @AnniID INT
AS
    SELECT TOP 5 OrderDetails.AnniID,
                 Anniversary.Title,
                 Sum(OrderDetails.Quantity) AS TotalNum
    FROM   OrderDetails
           INNER JOIN Anniversary
             ON OrderDetails.AnniID = Anniversary.AnniID
    WHERE  OrderId IN (
                      /* This inner query should retrieve all orders that have contained the anniID */
                      SELECT DISTINCT OrderId
                       FROM   OrderDetails
                       WHERE  AnniID = @AnniID)
           AND OrderDetails.AnniID != @AnniID
    GROUP  BY OrderDetails.AnniID,
              Anniversary.Title
    ORDER  BY TotalNum DESC

    RETURN
4

2 回答 2

0

您的查询与您的编写方式略有混淆;

首先,您在 AnniId 上加入了两个表:

FROM   OrderDetails
INNER JOIN Anniversary
   ON OrderDetails.AnniID = Anniversary.AnniID

其次,您需要 OrderDetails 表中的 OrderIdsAnniId = @AnniId

WHERE OrderId IN 
(
   /* This inner query should retrieve all orders that have contained the anniID */
   SELECT DISTINCT OrderId 
   FROM OrderDetails
   WHERE AnniID = @AnniID
)

但是你想要 AnniID 不等于 @AnniId 的 OrderDetails:

AND OrderDetails.AnniID != @AnniID

您的查询中有几个相互冲突的语句。你到底想完成什么?

于 2012-07-30T11:25:30.307 回答
0

看起来像你对我的陈述

WHERE   OrderId IN  
(     
    /* This inner query should retrieve all orders
       that have contained the anniID   */
    SELECT DISTINCT OrderId      
        FROM OrderDetails     
        WHERE AnniID = @AnniID 
) 
AND OrderDetails.AnniID != @AnniID

等于@AnniID不等于的OrderDetails 怎么可能@AnniID

于 2012-07-30T11:22:19.140 回答