Linq、双左连接和双计数
我希望将这个 SQL 语句转换为一个运行良好的 SQL 语句。高性能 LINQ 命令。我已经设法使用分组计数和关键成员来进行第一个计数,但不知道如何获得第二个计数。
select main.title, count(details.id) as details, count(messages.id) as messages
from main
left outer join details on main.id = details.mainid
left outer join messages on details.id = messages.detailid
group by main.title
这是我到目前为止所做的:
from main in Main
join detail in Details on main.Id equals detail.MainId into j1
from subdetail in j1.DefaultIfEmpty()
group main by main.Title into g
select new { Title = g.Key, Details = g.Count() }
欢迎任何建议!
编辑:24/03/2010 09.41
这个查询:
from main in Main
join detail in Details on main.Id equals detail.MainId into j1
from subdetail in j1.DefaultIfEmpty()
join message in Messages on subdetail.Id equals message.DetailId into j2
group main by main.Title into g
select new { Title = g.Key, Details = g.Count() }
生成这个 SQL 语句:
SELECT COUNT(*) AS [Detail], [t0].[Title]
FROM [Main] AS [t0]
LEFT OUTER JOIN [Detail] AS [t1] ON [t0].[Id] = [t1].[MainId]
LEFT OUTER JOIN [Messages] AS [t2] ON [t1].[Id] = [t2].[DetailId]
GROUP BY [t0].[Title]
所以,我快完成了!
法比安
I'm looking to translate this SQL statement to a well working & performant LINQ command. I've managed to have the first count working using the grouping count and key members, but don't know how to get the second count.
select main.title, count(details.id) as details, count(messages.id) as messages
from main
left outer join details on main.id = details.mainid
left outer join messages on details.id = messages.detailid
group by main.title
Here's what I've done so far:
from main in Main
join detail in Details on main.Id equals detail.MainId into j1
from subdetail in j1.DefaultIfEmpty()
group main by main.Title into g
select new { Title = g.Key, Details = g.Count() }
Any advice is welcome!
EDIT: 24/03/2010 09.41
This query:
from main in Main
join detail in Details on main.Id equals detail.MainId into j1
from subdetail in j1.DefaultIfEmpty()
join message in Messages on subdetail.Id equals message.DetailId into j2
group main by main.Title into g
select new { Title = g.Key, Details = g.Count() }
generates this SQL statement:
SELECT COUNT(*) AS [Detail], [t0].[Title]
FROM [Main] AS [t0]
LEFT OUTER JOIN [Detail] AS [t1] ON [t0].[Id] = [t1].[MainId]
LEFT OUTER JOIN [Messages] AS [t2] ON [t1].[Id] = [t2].[DetailId]
GROUP BY [t0].[Title]
So, I'm almost done!
Fabian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这样的事情行不通吗?
如果您有外键约束,LINQ 应该自动生成子关系,这样您就可以访问与 main 关联的每个详细信息的 main.Details,以及与 main 关联的每个消息的 main.Messages。
Wouldn't something like this work?
If you have foreign key constraints, LINQ should generate the child-relationships automatically, so you could access main.Details for each Detail associated with main, and main.Messages for each Message associated with main.