1

我有两张表ForumForumCateory。ForumCateoryId 是映射字段。

Forum表包含以下字段:

ForumId, Title,Description and ForumCategoryId

ForumCategory表包含 ForumCategoryId,ForumCategory

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

4

2 回答 2

0

尝试top 1在子查询中使用

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

或尝试在子查询中使用aggregate functionmin例如):

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        
                              )
于 2012-10-14T17:32:53.800 回答
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)
于 2012-10-14T17:40:59.013 回答