doupuzhimuhan9216 2015-08-08 17:11
浏览 17
已采纳

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

So I've started doing sales and slapped together a little setup to give me a bit of an advantage over my fellow sales people.

I have 2 databases - "clients" which has each client's particulars, and "clients_activity" which has entries that I add whenever I make contact with them.

All I need is a query that gets the latest activity from "clients_activity" for each unique user using the datetime field. What I've done gets the results but doesn't display the newest entry.. it looks like this:

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

It's of course somewhat insufficient and requires an extra little bit of wizardry, unfortunately my head is a bit numb at this point - any help would be appreciated!

  • 写回答

3条回答 默认 最新

  • douliexu5623 2015-08-08 17:28
    关注

    Below query is what you are looking for. You need to use order by clause before joining the tables.

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答