2012-10-14 8 views
1

J'ai deux tables Forum et ForumCateory. ForumCateoryId est le champ de mappage.Comment puis-je obtenir le premier enregistrement de la table des clés foriegn avec chaque enregistrement de la table des clés primaires?

Le tableau Forum contient les champs tels que:

ForumId, Title,Description and ForumCategoryId 

Le tableau ForumCategory contient ForumCategoryId,ForumCategory

je dois afficher tous les enregistrements de ForumCategory et top 1 titre et la description du Forum.

+0

"Top 1 titre et la description du forum" aura t-il le même ForumCategoryId avec ForumCategory? – aliassce

+0

Oui. Il existe une relation un à plusieurs entre ForumCategory et Forum. – Krishnan

Répondre

0

Essayez ti utilisation top 1 dans sous_requête

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

ou essayez d'utiliser aggregate function (min par exemple) sous-requête:

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   
          ) 
0

Je suppose que vous avez besoin pour chaque dernier Forum Catégorie Forum , donc j'ai commandé le forum par ForumId décroissant.

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 

vous pouvez aussi essayer quelque chose comme ça

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) 
Questions connexes