在我的数据库中,我有两个表:
动作
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| lead_id | int(11) | YES | UNI | NULL | |
| type | varchar(255) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
铅
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| status | varchar(255) | YES | | NULL | |
| created | datetime | NO | | NULL | |
| lead_id | int(11) | NO | MUL | NULL | |
+---------+--------------+------+-----+---------+----------------+
排行榜有点不寻常,因为潜在客户是非唯一的,并由lead_id
标识,因此可能会有多个潜在客户具有相同的lead_id
。
我想要做的是检索所有操作,然后将它们加入条件它们是最新的(MAX(created)
?)。
This回答部分解释了如何处理引导表,但是我无法找到如何以正确的方式在子查询上进行连接。
答案 0 :(得分:1)
有多种方法可以做到这一点。以下内容将条件放在on
子句中:
select a.*
from lead l join
action a
on l.lead_id = a.lead_id and
l.created = (select MAX(created) from leads l2 where l2.lead_id = l.lead_id)
您也可以使用显式聚合子查询执行此操作:
select a.*
from lead l join
action a
on l.lead_id = a.lead_id join
(select lead_id, max(created) as maxcreated
from lead l
group by lead_id
) lmax
on lmax.lead_id = l.lead_id and lmax.maxcreated = l.created;
答案 1 :(得分:0)
未经验证,但我认为您需要以下内容:
select action.*, max_leads.* from action left join
(select lead_id, max(created) from lead group by lead_id) max_leads
on action.lead_id = max_leads.lead_id