Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In MySQL, how to fetch limit values for all id's

SELECT selected_date, id, price1, price2 
from values 
WHERE id = 100 
order by 1 desc 
LIMIT 90

I am fetching top 90 values from table for each id.

If I want to get for multiple ID’s in one query and top 90 items for each id, How do I write the query?

This query is giving 90 items for the first id only.
Ideally I want 90+90=180 items for each of the id’s. How to get this??

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT selected_date, id, price1, price2 
from values 
WHERE id IN (100, 101) 
order by 1 desc 
LIMIT 90

This is giving me only 90 items from the first id.

version of MySQL: 8.0

>Solution :

If your MySql version supports window functions you could try the following

with t as (
    select selected_date, id, price1, price2,
    Row_Number() over(partition by id order by selected_date desc) rn
    from values 
    where id in (100, 101)
)
select selected_date, id, price1, price2
from t
where rn <= 90
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading