我有两张表accounts
和calls
。 Account
表包含帐户详细信息,call
表包含date_modified
等帐户ID以及parent_id
列中帐户ID的其他详细信息。
有很多记录,我需要一个查询来获取所有帐户的最后通话详情(最近一次通话)。
我试过这个但却无法得到结果。
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
)
答案 0 :(得分:1)
请尝试此查询并告诉我结果:
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)
答案 1 :(得分:1)
尝试此查询:它应该有效。
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