加入2个表,从另一个表中获取不同的最新条目

时间:2015-08-08 17:11:14

标签: php mysql join

所以,我开始做销售,并采取了一些设置,让我比其他销售人员更有优势。

我有2个数据库 - "客户"它包含每个客户的详细信息,以及" clients_activity"每当我与他们联系时,我都会添加条目。

我只需要一个查询来获取来自" clients_activity"的最新活动。对于使用datetime字段的每个唯一用户。我所做的事情得到了结果,但没有显示最新的条目..它看起来像这样:

SELECT
clients.client_name,
clients.id,
clients.client_id,
clients.institution,
clients.interested_in,

clients_activity.client_id,
clients_activity.contacted_on,
clients_activity.current_situation,
clients_activity.timestamp, 
clients_activity.contacted_by,
clients_activity.notes

FROM clients_activity

LEFT JOIN clients

ON clients.id = clients_activity.client_id

GROUP BY clients.client_name ORDER BY contacted_on DESC

它当然有些不足,需要额外的一点魔法,不幸的是我的头在这一点上有点麻木 - 任何帮助都会受到赞赏!

3 个答案:

答案 0 :(得分:3)

您需要先获取最新活动,然后再加入clients表。假设timestamp表中的clients_activity代表最新或最旧的,您可以使用以下

select
c.client_name,
c.id,
c.client_id,
c.institution,
c.interested_in,
ca.client_id as ca_client_id,
ca.contacted_on,
ca.current_situation,
ca.timestamp, 
ca.contacted_by,
ca.notes
from clients c 
join clients_activity ca on ca.client_id = c.client_id
join(
 select max(timestamp) as timestamp,client_id
 from clients_activity
 group by client_id
)t
on t.client_id= ca.client_id and t.timestamp = ca.timestamp

答案 1 :(得分:0)

假设您的实现支持公用表表达式,

WITH MaxDate_CTE AS
(
    SELECT
        client_id,
        MAX(timestamp) AS MaxTime
    FROM
        clients_activity
    GROUP BY
         client_id
)
SELECT
    a.*
FROM
    clients_activity a
        INNER JOIN MaxDate_CTE m ON a.client_id = m.client_id AND a.timestamp = m.MaxTime
ORDER BY
    a.contacted_on DESC;

答案 2 :(得分:0)

以下查询是您要找的内容。在加入表之前,您需要使用order by子句。

SELECT
    clients.client_name,
    clients.id,
    clients.client_id,
    clients.institution,
    clients.interested_in,
    c_activity.client_id,
    c_activity.contacted_on,
    c_activity.current_situation,
    c_activity.timestamp, 
    c_activity.contacted_by,
    c_activity.notes
FROM clients 
    LEFT JOIN (
        SELECT
            ca.client_id,
            ca.contacted_on,
            ca.current_situation,
            ca.timestamp,
            ca.contacted_by,
            ca.notes
        FROM clients_activity ca
        ORDER BY ca.contacted_on DESC
        ) c_activity
    ON clients.id = c_activity.client_id
GROUP BY clients.client_name;