这个T-SQL查询是否正确?

时间:2016-09-15 01:10:06

标签: tsql sql-server-2012

我的代码返回一个数据集,但是我不相信它们是准确的,我在使用子查询时有点失落。有人可以查看我的代码。我试图解决的问题来自T-SQL 2012书中的高级问题。问题告诉我:

获取包含“调味品”类别中至少一项的所有订单的订单ID,订单日期,客户ID和公司名称。在查询中使用类别名称。

这是我的代码:

SELECT 
    o.orderid, o.orderdate, o.custid, c.companyname
FROM 
    Sales.Orders AS o
JOIN 
    Sales.OrderDetails AS od ON o.orderid = od.orderid
JOIN 
    Sales.Customers AS c ON o.custid = c.custid
WHERE  
    qty > 1
    (SELECT categoryname FROM
        Production.Categories    
        WHERE categoryname = N'Condiments');

我的结果:

orderid    orderdate            custid  companyname
-------------------------------------------------------
10248   2006-07-04 00:00:00.000 85      Customer ENQZT
10248   2006-07-04 00:00:00.000 85      Customer ENQZT
10249   2006-07-05 00:00:00.000 79      Customer FAPSM
10250   2006-07-08 00:00:00.000 34      Customer IBVRG

表格结构:

客户

Sales.Customers
(
     custid       INT          NOT NULL IDENTITY,
     companyname  NVARCHAR(40) NOT NULL,
     contactname  NVARCHAR(30) NOT NULL,
     contacttitle NVARCHAR(30) NOT NULL
)

PK custid

订单

Sales.Orders
(
    orderid        INT          NOT NULL IDENTITY,
    custid         INT          NULL,
    empid          INT          NOT NULL,
    orderdate      DATETIME     NOT NULL
)

PK orderid
FK custid

类别:

Production.Categories
(
    categoryid   INT           NOT NULL IDENTITY,
    categoryname NVARCHAR(15)  NOT NULL,
    description  NVARCHAR(200) NOT NULL,

    CONSTRAINT PK_Categories PRIMARY KEY(categoryid)
);

ORDERDETAILS

Sales.OrderDetails
(
    orderid   INT           NOT NULL,
    productid INT           NOT NULL,
    unitprice MONEY         NOT NULL
    CONSTRAINT DFT_OrderDetails_unitprice DEFAULT(0),
    qty       SMALLINT      NOT NULL
)

由于Category表与OrdersCustomers没有任何关系,因此我必须是相关查询。非常感谢所有学习/教学反应。

1 个答案:

答案 0 :(得分:1)

我们去了,您的查询应该包含Products表,如下所示:

SELECT o.orderid, o.orderdate, o.custid, c.companyname
FROM Sales.Orders AS o
     JOIN Sales.OrderDetails AS od
     ON o.orderid = od.orderid
     JOIN Sales.Customers AS c
     ON o.custid = c.custid
     JOIN Production.Products d
     on od.ProductId = d.ProductId
     JOIN Production.Categories cat
     on cat.CategoryId = d.CategoryID
     and cat.categoryname = N'Condiments');

这可能足以让你入门。