MySQL使用max id离开了join

时间:2016-09-06 13:05:34

标签: mysql sql

我有一个名为tbl_messages的表格包含邮件。如果MessageReply是第一条消息,则每条消息的值都为0;如果是对另一条消息的回复,则消息ID为

我需要为每个根消息获取它的数据+它的最新响应日期。

我正在运行以下SQL过程:

SELECT 
    m1.*, m2.MessageID, m2.MessageDate 
FROM 
    tbl_messages as m1 LEFT JOIN tbl_messages as m2 
ON 
    m1.MessageID = m2.MessageReply 
WHERE 
    m1.MessageReply = '0' AND 
    (m1.MessageUser = '1' OR m1.MessageBusiness = '1') AND 
    m2.MessageID = (SELECT MAX(MessageID) FROM tbl_messages WHERE MessageReply = m1.MessageID) 
ORDER BY 
    m2.MessageID desc, m1.MessageID desc

我的问题是因为最后一个WHERE语句它没有返回左表中没有右表值的值。

我该如何解决?

2 个答案:

答案 0 :(得分:4)

当您在WHERE子句中编写语句时,它将过滤整个查询结果。

当您在加入左侧时在ON子句中编写该语句时,它将仅过滤左连接表,并且如果语句不匹配,则结果将是来自辅助表的NULL值。

SELECT 
    m1.*, m2.MessageID, m2.MessageDate 
FROM 
    tbl_messages as m1 LEFT JOIN tbl_messages as m2 
ON 
    m1.MessageID = m2.MessageReply 
    AND
    m2.MessageID = (SELECT MAX(MessageID) FROM tbl_messages WHERE MessageReply = m1.MessageID)

WHERE 
    m1.MessageReply = '0' AND 
    (m1.MessageUser = '1' OR m1.MessageBusiness = '1') 
ORDER BY 
    m2.MessageID desc, m1.MessageID desc

答案 1 :(得分:0)

如果你的id是增量的,你应该能够使用MAX()获得最新/最高日期和id

SELECT 
    m1.*, 
    MAX(m2.MessageID) AS reply_id, 
    MAX(m2.MessageDate) AS reply_date
FROM 
    tbl_messages as m1 
    LEFT JOIN tbl_messages as m2 ON 
    (
        m1.MessageID = m2.MessageReply 
    )
WHERE 
    m1.MessageReply = '0' AND 
    (m1.MessageUser = '1' OR m1.MessageBusiness = '1') 
GROUP BY
    m1.MessageID
ORDER BY 
    reply_date DESC, 
    m1.MessageID DESC

如果你的id不是增量的,你可以第三次加入表,后面的响应,以及那个没有后续响应的行是最新的回复。

SELECT 
    m1.*, 
    m2.MessageID AS reply_id, 
    m2.MessageDate AS reply_date
FROM 
    tbl_messages as m1 
    LEFT JOIN tbl_messages as m2 ON 
    (
        m1.MessageID = m2.MessageReply 
    )
    LEFT JOIN tbl_messages as m3 ON 
    (
        m1.MessageID = m3.MessageReply AND
        m3.MessageDate > m2.MessageDate
    )
WHERE 
    m1.MessageReply = '0' AND 
    (m1.MessageUser = '1' OR m1.MessageBusiness = '1') AND 
    m3.MessageReply IS NULL
GROUP BY
    m1.MessageID
ORDER BY 
    reply_date DESC, 
    m1.MessageID DESC

您可能希望在订单中COALESCE,以获取没有回复的邮件,最终到达您可能需要的位置,例如: ORDER BY COALESCE(m2.MessageDate, m1.MessageDate) DESC