我有两张桌子,Product和SalesProduct。
Product表示例记录(这里ProductID是主键):
ProductID | ProductCode | Name
----------+-------------+-----------
1 P001 Computer
2 p002 Laptop
3 p003 SpeakerSalesProduct表示例记录(这里ID是主键,ProductID是引用Products表的外键):
ID| SalesNo | ProductID
--+---------+-----------
1 S0001 1
2 S0002 2
3 S0003 3
4 S0004 1
5 S0005 2
6 S0006 3
7 S0007 1
8 S0008 2
9 S0009 3当我写这个查询时:
SELECT
SalesNo, SalesProduct.ProductID, Name
FROM
SalesProduct
JOIN
Product ON SalesProduct.ProductID = Product.ProductID它将工作得很好,并返回以下结果:
SalesNo | ProductID | Name
--------+-----------+---------
S0001 1 Computer
S0002 2 Laptop
S0003 3 Speaker
S0004 1 Computer
S0005 2 Laptop
S0006 3 Speaker
S0007 1 Computer
S0008 2 Laptop
S0009 3 Speaker但是当我尝试像这样选择TOP(3)行时:
SELECT TOP(3)
SalesNo, SalesProduct.ProductID, Name
FROM
SalesProduct
JOIN
Product ON SalesProduct.ProductID = Product.ProductID此查询将返回相同的产品:
S0001 1 Computer
S0004 1 Computer
S0007 1 Computer但我想要这样的结果:
S0001 1 Computer
S0002 2 Laptop
S0003 3 Speaker上面的查询出了什么问题?怎样才能得到预期的输出呢?
发布于 2018-03-18 01:09:59
SELECT TOP(3) sp.SalesNo, sp.ProductID, p.Name
FROM SalesProduct sp
INNER JOIN Product p ON SalesProduct.ProductID = Product.ProductID
ORDER BY sp.SalesNohttps://stackoverflow.com/questions/49339118
复制相似问题