简体   繁体   中英

Improve performance of query with correlated subquery

I have a table "book" that contains 2 columns: title and price. There are a number of books with different prices. I have came up with the following query, but how can I improve performance?

Select title from book as b 
where (
  select count(*) from book as t
  where t.price>b.price
) < 5

If you are using MySQL 8+ or later, then we can easily use ROW_NUMBER here:

WITH cte AS (
    SELECT title, ROW_NUMBER() OVER (ORDER BY price DESC) rn
    FROM book
)

SELECT title
FROM cte
WHERE rn <= 5;

This doesn't take into account the possibility of two or more books being tied for the same price. In that case, we might use a rank analytic function instead of row number.

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