改进实体框架中的嵌套查询
本文关键字:嵌套 查询 框架 实体 | 更新日期: 2023-09-27 17:56:57
我正在尝试编写linq到实体查询,如下所示:
var lst = (from rw in ctx.Reviews
where rw.RefId == 10
&& rw.UpdatedTime == (from inner in ctx.CompareReviews
where inner.RefId == 10
&& inner.ReviewNumber == rw.ReviewNumber
select inner.UpdatedTime).Max()
select rw).ToList();
我希望它将生成以下查询:
select *
from review rw
where rw.ref_id = 10
and rw.updated_time = (select max(irw.updated_time)
from review irw
where irw.ref_id = 10
and irw.review_number = rw.review_number)
但它没有,它会生成一个如下所示的查询:
select rw.id,
/* .. other fields */
(
select max(irw.updated_time)
from review irw
where irw.ref_id = 10
and irw.review_number = rw.review_number
) as updated_time
from review rw
where rw.ref_id = 10
如何使实体框架生成第一个查询。
请尝试以下查询:
SELECT id, <other_columns>
FROM review
WHERE ref_id = 10
ORDER BY updated_time DESC limit1;
注意:应为ref_id和updated_time字段编制索引。
根据您的更新要求:
SELECT review_number,id, <other_columns>
FROM
(SELECT id,ref_id,<other_columns> FROM review
WHERE ref_id = 10
ORDER BY updated_time DESC) a
GROUP BY review_number;