[英]Get Latest N numbers of records from table using where in condition
Need to fetch the latest 3 records from tables of each orderid(s)
related to storeid(s)
using WHERE IN
condition.需要使用
WHERE IN
条件从与storeid(s)
orderid(s)
的表中获取最新的 3 条记录。
For Eg:例如:
--------------------------
orderid storeid
1 2
5 2
7 2
15 5
18 5
25 5
29 9
65 9
78 9
------------------------
Here my Query:这是我的查询:
SELECT * FROM orders WHERE store_id IN('2', '5', '9') ORDER BY store_id
Thanks in advance.提前致谢。
using row_number()
you can get the latest 3 orderids
使用
row_number()
您可以获得最新的 3 个orderids
select * from orders o
inner join (
select row_number() over (partition by storeid order by orderid desc) rn, orderid
from orders) t1 on t1.orderid = o.orderid
where t1.rn <= 3
Here is the mysql solution to get n
number of rows for each store:这是 mysql 解决方案,用于获取每个商店的
n
行数:
SELECT
*
FROM
(
SELECT
store_id,
order_id,
@curRank := CASE WHEN @prevStore = store_id THEN @curRank + 1 ELSE 0 END AS rank,
@prevStore:= store_id AS prevStore
FROM orders a, (SELECT @curRank := 0, @prevStore := NULL) r
WHERE store_id IN('2', '5', '9')
ORDER BY 1 desc,2
)a
WHERE a.rank<3;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.