SQL MAX(m.time)不选择最高值

时间:2011-01-18 18:59:29

标签: sql mysql

这段代码:

SELECT m.message, 
          MAX(m.time) AS time, 
          m.sender, 
          m.receiver, 
          m.contact, 
          u.ufirstname
FROM( (SELECT message, 
                  receiver_uid AS receiver, 
                  sender_uid AS sender, 
                  time, 
                  receiver_uid AS contact 
             FROM messages 
            WHERE sender_uid = '$me' ) 
           UNION 
           (SELECT message, 
                   receiver_uid AS receiver, 
                   sender_uid AS sender, 
                   time, 
                   sender_uid AS contact 
              FROM messages 
             WHERE receiver_uid = '$me' ) ) AS m, 
         users AS u
   WHERE m.contact = u.uid
GROUP BY m.contact
ORDER BY time DESC;

我的问题是这件作品应该选择对话的最新消息。 这是数据库的格式:

Sender_uid | receiver_uid | message | time («What format should this be?)

第一部分检索“$ me”(=登录用户的用户ID)参与的所有消息。所以所有消息是'$ me'是发送还是接收。 第二部分应选择每个'对话'的最近时间(最高值)(=联系人ID,无论联系人是接收者还是发送者)

获取最新消息。 确实会给您一条来自对话的消息。

重要提示(?):我认为该脚本正在检索最近的消息,其中'$ me'是发件人。

我希望它收集最后一条消息,无论我是接收者还是发送者。

1 个答案:

答案 0 :(得分:1)

请停止滥用MySQL混合聚合和非聚合。虽然MySQL允许它,但是每个列的记录都是不可预测的,它们甚至不必来自同一条记录(同步)

SELECT m2.message, 
          m2.time AS time, 
          m2.sender, 
          m2.receiver, 
          m.contact, 
          u.ufirstname
FROM (
    SELECT
        case when sender_uid = '$me' then receiver_uid else sender_uid end Contact,
        max(time) maxtime
    FROM messages 
    WHERE sender_uid = '$me' or receiver_uid = '$me'
    group by case when sender_uid = '$me' then receiver_uid else sender_uid end
) AS m
INNER JOIN messages m2 on m.maxtime = m2.time
    and ((m2.sender_uid = '$me' and m2.receiver_uid = m.Contact)
        or
        (m2.receiver_uid = '$me' and m2.sender_uid = m.Contact))
INNER JOIN users AS u on m.contact = u.uid
ORDER BY time DESC;

@updated查询 - 看起来更复杂。

  • “联系人”是对话的另一方。
  • 内部OR仅用于通过表格一次。
  • 内部CASE语句用于获取另一方的ID。 如果'$ me'与发送者匹配,则接收者成为“联系人” 否则发件人是“联系人”
  • 与m2的连接使用3个属性 - 我,联系人(方向)和最长时间 此连接使用内部查询(maxTime)中的键来检索 表中的完整记录
  • 与用户进行最终加入以获取联系人的名字