我在MySQL数据库中有2个表。
tbl_clients
id | name
1 | Mike
2 | John
3 | Dave
.........
N | N
tbl_orders
id | order_date | price | client_id
1 | 2018-03-19 | 1000 | 1
2 | 2018-03-19 | 5000 | 2
3 | 2018-05-19 | 3000 | 3
................
N | N | N | N
出于某些统计原因,在我的任务中,我需要接受ID = 2和3的客户的前3个订单。
是否可以通过一个查询获取数据,我该如何获取?
答案 0 :(得分:0)
在MySQL 8.0中,您可以简单地使用row_number()
。较早版本中的一个选项是相关子查询-假设order_date
是唯一的:
select o.*
from tbl_orders o
where o.order_date <= (select o2.order_date
from tbl_orders o2
where o2.client_id = o.client_id
order by o2.order_date asc
limit 2, 1
);
如果您确实希望将其限制为仅2个客户端,则可以在外部查询中添加where o.client_id in (2, 3)
。