我有两张表Forum和ForumCateory。ForumCateoryId 是映射字段。
该Forum
表包含以下字段:
ForumId, Title,Description and ForumCategoryId
该ForumCategory
表包含
ForumCategoryId,ForumCategory
我需要显示来自ForumCategory的所有记录以及来自论坛的前 1 个标题和描述。
我有两张表Forum和ForumCateory。ForumCateoryId 是映射字段。
该Forum
表包含以下字段:
ForumId, Title,Description and ForumCategoryId
该ForumCategory
表包含
ForumCategoryId,ForumCategory
我需要显示来自ForumCategory的所有记录以及来自论坛的前 1 个标题和描述。
尝试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
)
我假设您需要每个论坛类别的最后一个论坛,所以我按 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)