您可以group byuser_id,然后添加一个having子句以仅包含具有count(distinct bag_id) >= 3.
然后limit到3,并order by获取最新日期max(created_at)
这有帮助吗?
实现看起来像这样:
select
user.id,
max(history.created_at) as third_bag_received_at
from
(
select
user.id,
max(history.created_at)
from
users
inner join bags
on user.id = bags.user_id
inner join history
on bags.id = history.bag_id
where history.state = 'processed'
group by
user.id
having
count(history.bag_id >= 3)
limit 3
order by 2 -- does this work in mySql? (It means "column 2" in MS SQL)
)
Limit 1
编辑:如何解决计算列中其他表的连接/聚合问题:
我可能不会将此添加为计算列,而是创建一个包含此要求所需的任何信息的视图,包括third_bag_received基于此查询的列。
但是,如果您确实需要将其实现为表格上的计算列:
我建议创建一个接受您user.id作为输入并返回值的用户函数third_bag_received_at(同样,基于上述查询的逻辑)。
然后从您的计算列中调用此函数。请参阅@user10635对此 SO 问题的回答。