2016-06-25 74 views
1

我有這個代碼根據登錄用戶的ID對消息進行分組,代碼的效果很好。但現在我希望做一些修改,我不知道要實現MySQL查詢,然後按最近分組條件排序

我的查詢代碼

$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); 

DB結構

enter image description here

簡要說明

比方說 *的登錄用戶$用戶

在數據庫中的用戶可以是senderIDreceiverID

$用戶刪除變量自己對話中,他的消息從更新爲 in senderdelete列或接收者刪除列*

是問題是: -

我將要修改的mysqli的查詢代碼,這增加了查詢

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

if $user is the receiver then receiverdelete should be value 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); 
+1

爲了避免未來的歧義,特別是在擴大的複雜條件下,儘量爲其中包裝等('$ user'= senderID和senderdelete = 0)OR('$ user'= receiverID和receiverdelete = 0) – DRapp

+0

我將在我的編程中使用這些更改@DRapp。我很滿意支持 –