I have Price_trend table in that m_id and c_id are foreign keys. I need m_id column 3,7 top two records.
Her is my db-fiddle
table: price_trend
id | c_id | m_id | date |
---|---|---|---|
1 | 1 | 3 | 2022-12-08 |
2 | 1 | 3 | 2022-12-06 |
3 | 1 | 3 | 2022-12-05 |
4 | 1 | 7 | 2022-12-03 |
5 | 1 | 7 | 2022-12-02 |
6 | 1 | 7 | 2022-12-01 |
My Attempt:
I have written the query up to this point, but am stuck on what to do next
select * from price_trend where c_id=1 and m_id in(3,7) limit 4;
I want result:
id | c_id | m_id | date |
---|---|---|---|
1 | 1 | 3 | 2022-12-08 |
2 | 1 | 3 | 2022-12-06 |
4 | 1 | 7 | 2022-12-03 |
5 | 1 | 7 | 2022-12-02 |
2
Answers
On MySQL 8+ we can use the
ROW_NUMBER()
window function:ROW_NUMBER()
assigns a sequence 1, 2, 3 to each record in a givenm_id
group, with the most recent record being assigned 1, the next most recent 2, and so on. In the outer query we then restrict to only records having the first two row numbers.In MySQL 5.X, you can use variables to generate the ranking index. Once you get it, you can select ranking values less or equal to 2.
Check the demo here.