我有两个表论坛和 ForumCateory 。 ForumCateoryId是映射字段。
Forum
表包含以下字段:
ForumId, Title,Description and ForumCategoryId
ForumCategory
表包含
ForumCategoryId,ForumCategory
我需要显示来自 ForumCategory 和前1个标题和论坛描述的所有记录。
答案 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)