0

我正在尝试将 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

如何使实体框架生成第一个查询。

4

1 回答 1

0

请尝试以下查询:

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;
于 2014-04-07T10:39:38.737 回答