SQL 查询 LINQ INNER JOIN
SQL query to LINQ INNER JOIN
我需要将 SQL 查询转换为 LINQ,但不知道如何做。
我有两个表:Bins 和 DataFromBins。
DataFromBins 包含引用 Bins.Id 的 BinId 列
我的查询所做的是从 DataFromBins 中为每个 BinId 选择最新的行,并从 Bins 中为这些 BinId 加入一些数据。
请帮忙:(
SELECT BinId, Address, Lon, Lat, MaxFillLevel, Distance
FROM (
SELECT DataFromBins.*
FROM (
SELECT DataFromBins.BinId, MAX(DataFromBins.Date) AS Date
FROM DataFromBins
GROUP BY DataFromBins.BinId
) AS latest_records
INNER JOIN DataFromBins ON DataFromBins.BinId = latest_records.BinId
AND DataFromBins.Date = latest_records.Date
) AS most_recent
INNER JOIN Bins ON most_recent.BinId = Bins.Id
我猜你正在寻找下面的代码。诀窍是拆分子查询;)
假设 _db
是你的上下文。
var latestRecords = from t in _db.DataFromBins
group t by t.BinId into g
select new
{
BinId = g.Key,
Date = (from t2 in g select t2.Date).Max()
};
var mostRecents = from itm in latestRecords
join bin in _db.DataFromBins on new {BinId = itm.BinId, Date =itm.Date } equals new {BinId = bin.BinId , Date =bin.Date}
select bin;
var finalQuery = from recent in mostRecents
join bin _db.Bins on recent.BinId equals bin.Id
select new {
bin.BinId,bin.Address, bin.Lon, bin.Lat, bin.MaxFillLevel, bin.Distance
}
我需要将 SQL 查询转换为 LINQ,但不知道如何做。 我有两个表:Bins 和 DataFromBins。 DataFromBins 包含引用 Bins.Id 的 BinId 列 我的查询所做的是从 DataFromBins 中为每个 BinId 选择最新的行,并从 Bins 中为这些 BinId 加入一些数据。
请帮忙:(
SELECT BinId, Address, Lon, Lat, MaxFillLevel, Distance
FROM (
SELECT DataFromBins.*
FROM (
SELECT DataFromBins.BinId, MAX(DataFromBins.Date) AS Date
FROM DataFromBins
GROUP BY DataFromBins.BinId
) AS latest_records
INNER JOIN DataFromBins ON DataFromBins.BinId = latest_records.BinId
AND DataFromBins.Date = latest_records.Date
) AS most_recent
INNER JOIN Bins ON most_recent.BinId = Bins.Id
我猜你正在寻找下面的代码。诀窍是拆分子查询;)
假设 _db
是你的上下文。
var latestRecords = from t in _db.DataFromBins
group t by t.BinId into g
select new
{
BinId = g.Key,
Date = (from t2 in g select t2.Date).Max()
};
var mostRecents = from itm in latestRecords
join bin in _db.DataFromBins on new {BinId = itm.BinId, Date =itm.Date } equals new {BinId = bin.BinId , Date =bin.Date}
select bin;
var finalQuery = from recent in mostRecents
join bin _db.Bins on recent.BinId equals bin.Id
select new {
bin.BinId,bin.Address, bin.Lon, bin.Lat, bin.MaxFillLevel, bin.Distance
}