简体   繁体   中英

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

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?

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) .

I cannot speak to why the second version would be faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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