我有以下 MySQL 表:
CREATE TABLE IF NOT EXISTS `conversations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user1_id` int(11) NOT NULL,
`user2_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user1_id_2` (`user1_id`,`user2_id`)
);
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`conversation_id` int(11) NOT NULL,
`sender_id` int(11) NOT NULL,
`recipient_id` int(11) NOT NULL,
`subject` varchar(64) NOT NULL,
`body` text NOT NULL,
`created` datetime DEFAULT NULL,
`is_deleted_by_sender` tinyint(3) unsigned NOT NULL DEFAULT '0',
`is_deleted_by_recipient` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
);
注意:在会话表中 user1_id 小于或等于 user2_id。
我想获取用户 X 的对话列表,其中每个对话都由该对话中用户 X 未删除的最后一条消息显示,并对结果进行分页。(就像facebook消息一样。无论最后一条消息是由X还是其他用户发送的,它都显示为显示消息。
我想出了分组最大的解决方案,它帮助我创建了以下子查询:
SELECT MAX(SubTable.id) AS id, conversation_id
FROM newtravel.messages AS SubTable
WHERE (
((SubTable.sender_id = 9) AND (SubTable.is_deleted_by_sender = 0))
OR
((SubTable.recipient_id = 9) AND (SubTable.is_deleted_by_recipient = 0))
)
GROUP BY conversation_id
我们可以将此子查询用作 $this->Paginator->settings 数组中的连接表吗?如果答案是肯定的,它应该生成如下查询:
SELECT m1.id, m1.conversation_id, m1.body, m1.sender_id, m1.recipient_id
FROM messages m1
INNER JOIN ( THE_SUB_QUERY_ABOVE ) m2
ON ( m1.conversation_id = m2.conversation_id
AND m1.id = m2.id )
ORDER BY m1.id DESC
这个最终查询返回想要的结果。但是我想不出在 PaginatorComponent 中设置正确选项的方法。对于这种查询,官方文档是不够的。那么,在这种情况下,我们该如何配置查找条件、连接、子查询等呢?