【问题标题】:Select inner join many-to-one relationship limiting number of results for child table选择内部连接多对一关系限制子表的结果数
【发布时间】:2012-03-19 14:02:49
【问题描述】:

我有以下表格:

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 的前10 个值,而不是返回每个TableB.Value 的每个TableB.Value

这样的查询是什么?

【问题讨论】:

    标签: sql sql-server-2008 sql-server-2008-r2 one-to-many many-to-one


    【解决方案1】:

    使用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%'        
    

    【讨论】:

    • @Lamak - 我最近才从 gbn 和 martin 那里学到的东西。
    猜你喜欢
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多