首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在SQL中选择前第n行的结果是错误的

在SQL中选择前第n行的结果是错误的
EN

Stack Overflow用户
提问于 2018-03-18 00:20:00
回答 3查看 59关注 0票数 1

我有两张桌子,ProductSalesProduct

Product表示例记录(这里ProductID是主键):

代码语言:javascript
运行
复制
ProductID | ProductCode | Name
----------+-------------+-----------
1               P001      Computer
2               p002      Laptop
3               p003      Speaker

SalesProduct表示例记录(这里ID是主键,ProductID是引用Products表的外键):

代码语言:javascript
运行
复制
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

当我写这个查询时:

代码语言:javascript
运行
复制
SELECT  
    SalesNo, SalesProduct.ProductID, Name 
FROM 
    SalesProduct
JOIN 
    Product ON SalesProduct.ProductID = Product.ProductID

它将工作得很好,并返回以下结果:

代码语言:javascript
运行
复制
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)行时:

代码语言:javascript
运行
复制
SELECT TOP(3) 
    SalesNo, SalesProduct.ProductID, Name 
FROM 
    SalesProduct
JOIN 
    Product ON SalesProduct.ProductID = Product.ProductID

此查询将返回相同的产品:

代码语言:javascript
运行
复制
S0001   1   Computer
S0004   1   Computer
S0007   1   Computer

但我想要这样的结果:

代码语言:javascript
运行
复制
S0001         1       Computer
S0002         2       Laptop
S0003         3       Speaker

上面的查询出了什么问题?怎样才能得到预期的输出呢?

EN

Stack Overflow用户

发布于 2018-03-18 01:09:59

代码语言:javascript
运行
复制
SELECT TOP(3) sp.SalesNo, sp.ProductID, p.Name 
FROM SalesProduct sp
INNER JOIN Product p ON SalesProduct.ProductID = Product.ProductID
ORDER BY sp.SalesNo
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49339118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档