简体   繁体   English

从两个表联接中获取每个记录的最后修改值?

[英]Get last modified values for each records from two tables joins?

I have two tables accounts and calls . 我有两个表accountscalls Account table contain the Account details and call table contain the call details like date_modified and others with account id in parent_id column. Account表包含帐户详细信息, call表包含呼叫详细信息,例如date_modified和其他在parent_id列中具有帐户ID的呼叫。

There are lots of the records and I need a query which fetch all the accounts with their last call details (Most recent call). 有很多记录,我需要一个查询,该查询将提取所有具有最近呼叫详细信息(最近呼叫)的帐户。

I have tried this but not able to get the result. 我已经尝试过了,但是无法获得结果。

SELECT accounts.id, accounts.name, calls.name subject 
FROM accounts 
INNER JOIN calls ON accounts.id = calls.parent_id 
WHERE accounts.id=(
   SELECT c.parent_id 
   FROM calls c 
   WHERE c.parent_id = calls.parent_id 
   ORDER BY c.date_modified DESC LIMIT 1
)

Please try this query and let me know the result: 请尝试此查询,并让我知道结果:

SELECT accounts.id, accounts.name, calls.name subject 
FROM accounts 
INNER JOIN calls ON accounts.id = calls.parent_id 
WHERE calls.date = (
   SELECT max(c.date)
   FROM calls c 
   WHERE c.parent_id = calls.parent_id)

Try this query: it should work. 试试这个查询:它应该可以工作。

SELECT * FROM Accounts A
INNER JOIN
(
    SELECT 
        c.parent_id
        ,c.name
        ,c.date_modified
    FROM calls C
    INNER JOIN 
    (
        SELECT 
            parent_id
            ,MAX(date_modified) call_date
        FROM calls 
        GROUP BY parent_id
    ) CC ON CC.parent_id = c.parent_id AND CC.call_date = c.date_modified

) CCC ON CCC.parent_id = A.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM