0

在我的数据库中,我有两个表:

行动

+--------------+--------------+------+-----+---------+----------------+
| 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)

这个答案部分解释了如何处理潜在客户表,但是我不知道如何以正确的方式对子查询进行连接。

4

2 回答 2

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;
于 2013-07-25T14:03:59.103 回答
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
于 2013-07-25T14:05:05.657 回答