[英]MySQL Join with min and max date
I have two tables我有两张桌子
profile
--------
id
name
Profile_dates
--------------
id
profile_id
entry_date
The tables have 1 to many relationships表有一对多的关系
I want to get min and max entry_date for each profile like我想为每个配置文件获取最小和最大 entry_date,例如
id
name
profile_dates.first_date
profile_dates.last_date
the profiles_dates table can have thousands of entries per profile. profile_dates 表中的每个配置文件可以包含数千个条目。 The simple join was very expensive for me.
简单的加入对我来说非常昂贵。 Is there another option?
还有其他选择吗?
simply join two tables and group by id:只需加入两个表并按 id 分组:
select p.id , name , min(pd.entry_date) first_date, max(pd.entry_date) last_date
from profiles p
left join Profile_dates pd
on p.id = pd.id
group by p.id , name
Sometimes subquery performance is far better than left join.有时子查询的性能远远好于左连接。 Please try this simple solution.
请尝试这个简单的解决方案。
id, name, (select min(entry_date) from Profile_dates pd where pd.profile_id=p.id) first_date,
(select max(entry_date) from Profile_dates pd where pd.profile_id=p.id) last_date
from profile p
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.