简体   繁体   English

有没有办法将更快的有序 SQL TOP 1 查询作为实体框架查询?

[英]Is there a way to make the faster ordered SQL TOP 1 query as Entity Framework query?

Here is two ways to get the top 1 row from a table ordered这是从有序表中获取前 1 行的两种方法

Slower:慢点:

select top 1 * 
from movies m
where m.Distributor = 'any'
order by m.IMDB_Rating desc

Faster:快点:

select top 1 m.* 
from movies m
left join movies m2 on m.Distributor = m2.Distributor 
                    and m2.IMDB_Rating > m.IMDB_Rating
where m.Distributor = 'any' 
  and m.IMDB_Rating is not null 
  and m2.id is null 

The first one is simpler, but the second one is faster.第一个更简单,但第二个更快。

So, is there a way to make the second query using Entity Framework?那么,有没有办法使用实体框架进行第二次查询?

If there is no way to make this query in EF or EF Core, could you give me another query as fast as the second one if it is possible?如果无法在 EF 或 EF Core 中进行此查询,如果可能的话,您能否像第二个查询一样快地给我另一个查询?

I'm sorry if it is duplicated, I can't find any answer to my question对不起,如果它是重复的,我找不到我的问题的任何答案

Thanks a lot!非常感谢!

For this query:对于此查询:

select top (1) m.*
from movies m
where m.Distributor = 'any'
order by m.IMDB_Rating desc;

You want an index on movies(Distributor, IMDB_Rating desc) .你想要一个关于movies(Distributor, IMDB_Rating desc)的索引movies(Distributor, IMDB_Rating desc)

I cannot speak to why the second version would be faster.我无法解释为什么第二个版本会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM