我需要将最近的动作(如果有的话)与每个节点相关联。下面的SQL查询对我这样做:
select n.*, o.* from Nodes n
left outer join (
select min(s.ActionAt) as ActionAt, min(s.Ahead) as Ahead, s.NodeId
from SuggestedActions s
group by s.NodeId
) o1
on o1.NodeId=n.Id
left outer join SuggestedActions o
on o.NodeId=o1.NodeId and o.ActionAt=o1.ActionAt and o.Ahead=o1.Ahead
但我无法使用LINQ制定相同的查询。我已经离开了选择最近操作的联接,我不知道如何继续加入更多数据:
from node in db.Nodes
join no in db.SuggestedActions on node.Id equals no.NodeId into no1
from o1 in no1.DefaultIfEmpty()
group o1 by node.Id into go1
select new {
NodeId = go1.Key,
ActionAt = go1.Min(c => c.ActionAt),
Ahead = go1.Min(c => c.Ahead)
} ...
答案 0 :(得分:1)
试试这个,它没有经过测试,但可能会给你一个方向:
var nodeActions = from node in db.Nodes
join action in db.SuggestedActions on node.Id equals action.NodeId into actions
from action in actions.DefaultIfEmpty()
select new { node, action };
var minNodes = from nodeAction in nodeActions
group nodeAction by nodeAction.node.Id
into groupedActions
select new
{
NodeId = groupedActions.Key,
ActionAt = groupedActions.Min(c => c.action.ActionAt),
Ahead = groupedActions.Min(c => c.action.Ahead)
};
var result = from minNode in minNodes
join nodeAction in nodeActions on new { Id = minNode.NodeId, minNode.ActionAt, minNode.Ahead }
equals new { nodeAction.node.Id, nodeAction.action.ActionAt, nodeAction.action.Ahead } into nodeActionJ
from action in nodeActionJ
select action;