2011-01-25 56 views
0

我想知道如何在Linq中编写下列SQL语句。我尝试过,但没有运气。如何在Linq中编写SQL查询语句SQL

/*Variable*/ 
topicId = '4a31c2ee-48af-4b87-b300-112acb822ad0' 

select * from Contents c 
left join ContentToTopicRelations ctr on ctr.ContentId = c.ContentId and ctr.TopicId = topidId 
where ctr.ContentId is null 

基本上,我想获得的所有不在ContentToTopicRelations表特定topicId内容。

回答

2

dataContext.Contents.Where(c => 
    !dataContext.ContentToTopicRelations.Any(ctr => 
    ctr.ContantId == c.ContentId && 
    ctr.TopicId == topicId)) 

它是相同的select * from Content where not exists(...)。在一般情况下,它比左连接和检查空(它取决于表的统计信息,但..),因为它会(一般情况下)半左连接,而不是左连接(在执行计划中) 。

对于左连接本身使用像下面的代码(但我建议使用代码为您的工作产生not exists):


from c in dataContext.Contents 
join tempCTR in dataContext.ContentToTopicRelations 
    on new { c.ContentId, topicId) equals new { tempCTR.ContentId, tempCTR.TopicId } 
    into tempCTRCollection 
    from ctr in tempCTRCollection.DefaultIfEmpty() 
where ctr == null 
select c 
+0

太好了!非常感谢。 – 2011-01-25 19:19:43

-1

topicvariable =“sdfsdfsdfsdf sdfsdfsdfsdfsdfsdfsdfsd”;

VAR结果=从C在内容 其中c.TopicId = topicvariable 选择C;

0
topicId = '4a31c2ee-48af-4b87-b300-112acb822ad0' 

IQueryable<Content> query = 
    from c in dataContext.Contents 
    where !c.ContentToTopicRelations.Any(ctr => ctr.TopicId == topicId) 
    select c;