MySQL Left Outer Join, MAX() and other columns
I have one table which stores all outbound SMS text messages. The second table stores a number of delivery receipts for each message (between 1 and 20 delivery receipts per message).
I have the following 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
There are 2 delivery receipts for message #466182.
The correct dlr_id
is returned (the most recent one) however, the dlr_status
that is returned is the first one. dlr_status
should be 5 instead of 2.
Any help would be very much appreci开发者_Python百科ated.
change to this:
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'
Just a minor tweak to your query should do:
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
Please check.
精彩评论