如何从外键表中获取前一条记录以及每个主键表记录?

时间:2012-10-14 17:22:25

标签: sql

我有两个表论坛 ForumCateory 。 ForumCateoryId是映射字段。

Forum表包含以下字段:

ForumId, Title,Description and ForumCategoryId

ForumCategory表包含 ForumCategoryId,ForumCategory

我需要显示来自 ForumCategory 前1个标题和论坛描述的所有记录。

2 个答案:

答案 0 :(得分:0)

在子查询中尝试使用top 1

select  *
from ForumCategory FC
join (select top 1 ForumId, Title,Description, ForumCategoryId
      from Forum 
      where F.ForumCategoryId = FC.ForumCategoryId 
     ) F 

或尝试在子查询中使用aggregate function(例如min):

select  *
from ForumCategory FC
join Forum F on  F.ForumCategoryId = FC.ForumCategoryId
             and F.ForumId = ( select min(F2.ForumId)
                               from Forum F2
                               where F2.ForumCategoryId = F.ForumCategoryId        
                              )

答案 1 :(得分:0)

我假设您需要每个论坛类别的最后一个论坛,所以我通过ForumId降序订购了论坛。

select
    FC.ForumCategoryId,
    FC.ForumCategory,
    F.Title as ForumTitle,
    F.Description as ForumDescription
from ForumCategory as FC
    outer apply
    (
        select top 1 TT.*
        from Forum as TT
        where TT.ForumCategoryId = FC.ForumCategoryId
        order by TT.ForumId desc
    ) as F

你也可以尝试这样的事情

select top 1 with ties
    FC.ForumCategoryId,
    FC.ForumCategory,
    F.Title as ForumTitle,
    F.Description as ForumDescription
from @ForumCategory as FC
    left outer join @Forum as F on F.ForumCategoryId = FC.ForumCategoryId
order by
    row_number() over (partition by FC.ForumCategoryId order by F.ForumId desc)