2014-12-04 125 views
0

嗨,我有一个表名messages我想从两个用户之间的聊天对话中获得最后一条消息。如何从聊天对话中获取最新消息?

表 -

id from_id to_id text  created 
======================================== 
1  1  2  hi  2014-12-01 10:30:10 
2  2  1  Hello  2014-12-01 10:30:20 
3  3  1  Hi chinu 2014-12-01 10:32:02 
4  3  1  hw r u? 2014-12-01 10:32:22 
5  2  1  h r u? 2014-12-01 10:33:01 

请检查我的查询=

//$user_id=$this->Session->read('Auth.User.id'); 
$user_id=1; 
$fields=array('DISTINCT(Message.from_id), Message.id, Message.text, Message.created'); 

    $this->Paginator->settings = array(
      'conditions'=>array('Message.to_id'=>$user_id), 
      'limit' => 30, 
      'order' => array(
       'Message.created' => 'DESC', 
       'Message.id' => 'DESC' 
      ), 
      'fields'=>$fields, 
      'group'=>array('Message.from_id') 
    ); 
    $inbox = $this->Paginator->paginate('Message'); 
    pr($inbox); 
    $this->set('inbox', $inbox); 

我想2和3 ID的最后消息会话。输出看起来像 -

id from_id to_id text  created 
======================================== 
5  2  1  h r u? 2014-12-01 10:33:01 
4  3  1  hw r u? 2014-12-01 10:32:22 

请帮助我。如果你不知道cakephp,请在这里发布核心的PHP MySQL查询。

感谢 chatfun

+0

预期的输出并不像'3'之间2和看起来像'2和1''之间和3 1 ' – 2014-12-04 13:28:52

+0

是的,但我不想列出我自己的ID – Developer 2014-12-04 13:29:28

+0

添加'WHERE'子句'WHERE Message.from_id <> $ user_id' – divaka 2014-12-04 13:35:13

回答

0

请检查该查询 -

SELECT * FROM (SELECT DISTINCT * FROM messages WHERE (from_id=1 OR to_id=1) ORDER BY created DESC) as m GROUP BY `from_id` 
+1

感谢它的工作正常。 :) – Developer 2014-12-04 14:15:29

0

我想这条查询工作(虽然我不明白为什么“to_id” = 1的预期输出,也许我没有得到你的目的右)

SELECT 'id', 'from_id', 'to_id', 'text', 'created' 
FROM Message 
WHERE ('from_id' = 2 AND 'to_id' = 3) OR ('from_id' = 3 AND 'to_id' = 2) 
ORDER BY created DESC 
LIMIT 1 
+0

你刚刚使用静态ID'2'和'3'。假设我与另外1000人聊天。那我该怎么办? – Developer 2014-12-04 13:32:12

+3

@Chatfun你的问题说两个用户之间的最新对话。如果这不是您正在寻找的内容,请编辑该问题。 – AdamMc331 2014-12-04 13:36:58

+0

是的,我想通过用户对话获取所有最后的消息组。 – Developer 2014-12-04 13:38:44

0

查询这看起来像实现你在找什么,即从每个from_id

select t1.* from Message 
t1 left join Message t2 
on t1.from_id = t2.from_id 
and t1.id<t2.id where t2.id is null; 

你获得最后一次谈话一个主键id auto_incremented,因此它可以用于比较而不是日期。

或者

select t1.* from Message t1 
where not exists (
select 1 from Message t2 where t1.from_id = t2.from_id and t1.id < t2.id 
);