我有以下表格:
create table TableA (
Id int primary key identity,
Name varchar(80) not null
)
create table TableB (
Id int primary key identity,
TableA_Id int not null foreign key references TableA(Id),
Value varchar(80) not null
)
我想写一个类似于
的查询select TableA.Name, TableB.Value
from TableA
inner join TableB on TableA.Id = TableB.TableA_Id
where TableA.Name like 'a%'
order by TableB.Value asc
除了我只想要 TableB.Value
的每个 TableA_Id
中的前 10 个(按 TableB.Value
升序排列)。
我不想返回每个 TableA.Name
的每个 TableB.Value
,我只想返回每个 TableA.Name
的前 10 个值。
这样的查询是什么?
最佳答案
使用 CROSS APPLY
.
CROSS APPLY
允许您
- 在子选择中使用
TOP
- 在子选择中使用
ORDER BY
- 将外部选择的每一行与子选择中的每一行匹配
SQL语句
SELECT TableA.Name
, b.Value
FROM TableA
CROSS APPLY (
SELECT TOP 10 *
FROM TableB
WHERE TableA.Id = TableB.TableA_Id
ORDER BY
TableB.Value
) b
WHERE TableA.Name LIKE 'a%'
关于sql - 选择inner join多对一关系限制子表的结果数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9771584/