简体   繁体   中英

Using the LIMIT function to display the 1st, 2nd and 3rd row, with the MAX customer rating using MySQL

I need to display the 1st, 2nd and 3rd names in the table with the highest customer rating. I created done the following query:

This query display the 1st, 2nd and 3rd names in the table,

SELECT *
FROM donuts
WHERE customer_rating
LIMIT 1,3;

I tried to use the MAX function to get the 3 highest customer ratings but I get a blank table.

SELECT MAX(customer_rating), donutName
FROM donuts
WHERE customer_rating
LIMIT 1,3;

Any suggestions,

Use ORDER BY

SELECT *
FROM donuts
ORDER BY customer_rating DESC
LIMIT 0, 3

The reason you got an empty result is because LIMIT 1, 3 prints the 2nd, 3rd, and 4th entries, not the 1st, 2nd, and 3rd entries, because LIMIT is zero-based (unlike just about everything else in SQL). But when you use an aggregate function like MAX() you only get one row of results (all the results are combined into a single maximum), so there is no 2nd entry.

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