我有一个包含以下列的消息表
id | message | toId | fromId | {few more columns}
我正在尝试列出最近的会话列表。考虑一个id为1的i与id为2的聊天
的情况有些行会像
1 | First Message | 1 | 2 | {few more columns}
2 | Sec Message | 2 | 1 | {few more columns}
3 | Third Message | 1 | 3 | {few more columns}
以下是我根据消息获取唯一对话的代码
$result = $this->Message->find('all', array(
'conditions' => $conditions,
'joins' => array(
array(
'table' => 'users',
'alias' => 'from',
'type' => 'LEFT',
'conditions' => array(
'from.id = Message.from',
)
),
array(
'table' => 'users',
'alias' => 'to',
'type' => 'LEFT',
'conditions' => array(
'to.id = Message.to',
)
),
),
'fields' => array('from.id','from.firstname','from.username', 'from.lastname','from.imagePath',
'to.id','to.firstname','to.username', 'to.lastname','to.imagePath',
'Message.*'),
'order' => array('Message.created DESC'),
'limit' => 20,
'offset' => $offset * 20,
));
以上代码只是简单地获取所有消息并附加其用户。但是我不知道如何根据独特的对话设置条件。
在上面的示例中,有两个对话,介于1和2之间,介于1和3之间
如何仅列出2条具有唯一组合的响应消息
“SELECT
From
。id
,From
。firstname
,From
。username
,From
。lastname
,From
。imagePath
,To
。id
,To
。firstname
,To
。username
,To
。lastname
,To
。imagePath
,Message
。* FROMxxxx
。messages
ASMessage
LEFT JOINxxxx
。users
ASTo
开(Message
。to
=To
。id
)LEFT JOINxxxx
。users
ASFrom
开(Message
。from
=From
。id
)LEFT JOINxxxx
。messages
ASmessage
ON(({Message
。from
=message
。from
和Message
。to
=message
。to
)或(Message
。from
=message
。to
和Message
。to
=message
。from
))和Message
。created
<message
。created
)WHEREmessage
。id
IS NULL ORDER BYMessage
。created
DESC LIMIT 20“,
答案 0 :(得分:1)
要从每个唯一的toId和fromId的消息中获取最新的对话,您可以在on()
部分
SELECT m.*
FROM
message m
LEFT JOIN message m1 ON (
(
(m.fromId = m1.fromId AND m.toId = m1.toId )
OR
(m.fromId = m1.toId AND m.toId = m1.fromId )
)
AND m.created < m1.created
)
WHERE m1.id IS NULL
ORDER BY m.id
稍后,您可以使用上述查询加入用户表以获取用户相关信息