MySQL查询,分组依次按最新顺序排序

时间:2016-06-25 20:23:28

标签: php mysql mysqli

我有这个代码根据登录用户的ID对邮件进行分组,代码工作得很好。但现在我想做一些我不知道要实施的修改

我的查询代码

 $query_messages = mysqli_query($link,"SELECT 
      PreQuery.*,
      m2.message,
      m2.senderID,
      m2.receiverID
   from
      ( SELECT 
              if( m.senderID < m.receiverID, m.senderID, m.receiverID ) as Person1,
              if( m.senderID < m.receiverID, m.receiverID, m.senderID ) as Person2,
              max( m.messageID ) as LastMessageIDPerChat,
              max( m.date ) as LastMessageDate
           FROM 
              messages m
           WHERE 
                   '$user' IN ( senderID, receiverID ) 
           GROUP BY
              Person1, 
              Person2
           ORDER BY 
              m.date ASC
           LIMIT 10 ) PreQuery

         JOIN messages m2
            on PreQuery.LastMessageIDPerChat = m2.messageID    ORDER BY 
              date DESC");
$row_messages = mysqli_fetch_assoc($query_messages);
$totalRows_messages = mysqli_num_rows($query_messages);

数据库结构

enter image description here

简要说明

让我们说 *登录用户的变量为 $ user

在数据库中,用户可以是 senderID receiverID

$ user 删除其对话时,他的消息会在senderdelete列或receiverdelete列* 0 更新为 1 >

问题是: -

我希望修改MySQLI查询代码并将其添加到查询

if $user is the sender then senderdelete should be value 0

if $user is the receiver then receiverdelete should be value 0

任何帮助?

1 个答案:

答案 0 :(得分:0)

我在where子句中添加了它,它似乎正在工作

WHERE 
'$myid' IN ( senderID ) AND senderdelete = 0 
OR
'$myid' IN ( receiverID ) AND receiverdelete = 0 

完整更新的代码

 $query_messages = mysqli_query($link,"SELECT 
      PreQuery.*,
      m2.message,
      m2.senderID,
      m2.receiverID,
      m2.senderdelete,
      m2.receiverdelete
   from
      ( SELECT 
              if( m.senderID < m.receiverID, m.senderID, m.receiverID ) as Person1,
              if( m.senderID < m.receiverID, m.receiverID, m.senderID ) as Person2,
              max( m.messageID ) as LastMessageIDPerChat,
              max( m.date ) as LastMessageDate
           FROM 
              messages m
           WHERE 
                   '$myid' IN ( senderID) AND senderdelete = 0 OR '$myid' IN ( receiverID) AND receiverdelete = 0 

           GROUP BY
              Person1, 
              Person2
           ORDER BY 
              m.date ASC
           LIMIT 10 ) PreQuery

         JOIN messages m2
            on PreQuery.LastMessageIDPerChat = m2.messageID    ORDER BY 
              date DESC");
$row_messages = mysqli_fetch_assoc($query_messages);
$totalRows_messages = mysqli_num_rows($query_messages);