我有一个表存储所有出站SMS短信。第二个表存储每封邮件的多个送达回执(每封邮件的送达收据在1到20之间)。
我有以下SQL:
SELECT
messages_sent.id,
messages_sent.user_id,
messages_sent.api_key,
messages_sent.to,
messages_sent.message,
messages_sent.sender_id,
messages_sent.route,
messages_sent.submission_reference,
messages_sent.unique_submission_reference,
messages_sent.reason_code,
messages_sent.timestamp,
MAX(delivery_receipts.id) AS dlr_id,
delivery_receipts.dlr_status
FROM
messages_sent
LEFT OUTER JOIN
delivery_receipts
ON
messages_sent.id = delivery_receipts.message_id
WHERE
message_id = '466182'
GROUP BY
messages_sent.id
消息#466182有2个送达回执。
返回正确的dlr_id
(最近的一个)但是,返回的dlr_status
是第一个。 dlr_status
应为5而不是2。
非常感谢任何帮助。
答案 0 :(得分:0)
改为:
Select m.id, m.user_id, m.api_key, m.to,
m.message, m.sender_id, m.route,
m.submission_reference,
m.unique_submission_reference,
m.reason_code, m.timestamp,
d.id dlr_id, d.dlr_status
From messages_sent m
Left Join delivery_receipts d
On d.message_id = m.id
And d.dlr_id = (Select Max(dlr_id)
From delivery_receipts
Where message_id = m.id)
Where message_id = '466182'
答案 1 :(得分:0)
只需对您的查询稍作调整即可:
SELECT
m.id, m.user_id, m.api_key, m.to, m.message, m.sender_id, m.route,
m.submission_reference, m.unique_submission_reference, m.reason_code,
m.timestamp, MAX(d.id) AS dlr_id,
(select d1.dlr_status
from delivery_receipts d1
where d1.id = max(d.id)) as dlr_status
FROM
messages_sent m
LEFT OUTER JOIN
delivery_receipts d
ON
m.id = d.message_id
AND
d.message_id = '466182'
GROUP BY
m.id
请检查。