2017-01-12 66 views
1

我正在使用laravel框架5.3。執行查詢後,我得到一個錯誤的結果。我有兩個表一個是用戶和其他的message.Here是我的方案如何從消息表中與每個其他用戶的所有會話中獲取最後一條消息?

enter code here 
User table- 

id name 
    1  a 
    2  b 
    3  c 


Message table: 
id sender_id receiver_id message 
1  1    2   hii 
2  2    1   hello 
3  1    3   hiiii 

現在我想獲取這些用戶有SENDER_ID這裏receiver_id 之間的最後一條消息是我的代碼: -

enter code here 
$coreQueryUser=DB::select(
     ' 
      select m.* ,u.* 
      from 
       messages m 
       inner join (
       select max(id) as maxid 
       from messages 
       where messages.sender_id = 1 // here i am sending userid is 1 
       group By (if(sender_id > receiver_id, sender_id, receiver_id)), 
       (if(sender_id > receiver_id, receiver_id, sender_id)) 
       ) t1 on m.id=t1.maxid 
       join 
       users u ON u.id = (CASE WHEN m.sender_id = 1 
            THEN m.sender_id 
            ELSE m.receiver_id   
           END) 
     ' 
     ); 

注意 - 我想找到所有已與用戶ID(1)提前:)

回答

0

使用ORDER BY短語 由於最後的消息,並限制你的結果使用LIMIT
我的回答是假設id行你主鍵,這是自動遞增代碼的

編輯\

enter code here 
$coreQueryUser=DB::select(
    ' 
     select m.* ,u.* 
     from 
      messages m 
      inner join (
      select max(id) as maxid 
      from messages 
      where messages.sender_id = 1 // here i am sending userid is 1 
      group By (if(sender_id > receiver_id, sender_id, receiver_id)), 
      (if(sender_id > receiver_id, receiver_id, sender_id)) 
      ) t1 on m.id=t1.maxid 
      join 
      users u ON u.id = (CASE WHEN m.sender_id = 1 
           THEN m.sender_id 
           ELSE m.receiver_id   
          END) 
     ORDER BY m.id DESC LIMIT 1 
    ' 
    ); 
+0

我想查詢一樣,將取回的所有對話用戶標識爲1的最後一條消息 –

相關問題