选择最后一个不同的对

时间:2016-03-30 09:29:21

标签: php mysql

好的,我们有收件箱表,用于保存用户发送给对方的邮件。这是表格:

CREATE TABLE IF NOT EXISTS `inbox` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`fromid` int(10) unsigned NOT NULL DEFAULT '0',
`toid` int(10) DEFAULT NULL,
`message` text CHARACTER SET utf8 NOT NULL,
`time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
KEY `toid` (`toid`),
KEY `fromid` (`fromid`),
KEY `fromid_2` (`fromid`,`toid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1  ;

fromid和toid是用户的id。我们有他们的ID,发送消息的时间。我们需要的是一个查询,它将返回“我们的用户”(管理员)未回复的所有邮件。 表帐户跟踪用户。简化:

CREATE TABLE IF NOT EXISTS `accounts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`our` int(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

基本上,我们需要一个查询,向用户提供管理员(我们的用户)未收到的WHOSE消息,他们的计数以及他们发送到ADMIN的最后一条消息的日期,从最后一个到最早的排序。

到目前为止,我们只有一些基本的查询,我们没有提出任何可以发布的合理内容。

提前致谢。

编辑:从我看到的情况来看,我们首先需要在收件箱表中找到两个DISTINCT用户的最后一次互动...然后检查&仅过滤发送给我们用户的那些

2 个答案:

答案 0 :(得分:0)

这个怎么样?

SELECT i.* FROM inbox as i 
WHERE (i.toid, i.fromid) NOT IN 
(SELECT i2.fromid, i2.toid FROM inbox as i2 WHERE i2.`time` >= i1.`time` AND i2.id = 1);

使用join的另一种方式:

SELECT DISTINCT i1.* 
FROM inbox as i1 LEFT JOIN inbox as i2 
    ON  i1.toid = 1 AND 
        i1.fromid = i2.toid AND 
        i1.toid = i2.fromid AND 
        i1.`time` <= i2.`time`
WHERE i2.id IS NULL;

答案 1 :(得分:0)

下面介绍了两种可能的解决方案:LEFT JOIN解决方案应该表现更好。

LEFT JOIN解决方案

SELECT 
 i.fromid, COUNT(*) AS unread, MAX(i.time) AS lastmsg 
FROM inbox AS i 
INNER JOIN accounts AS a 
 ON i.toid = a.id 
LEFT JOIN inbox AS i2 
 ON i.fromid = i2.toid AND i.toid = i2.fromid AND i.time <= i2.time 
WHERE a.our = 1 AND i2.id IS NULL
GROUP BY i.fromid
ORDER BY lastmsg DESC;

不在解决方案中

SELECT 
 i.fromid, COUNT(*) AS unread, MAX(i.time) AS lastmsg
FROM inbox AS i 
INNER JOIN accounts AS a ON i.toid = a.id 
WHERE a.our = 1 AND 
 (i.toid, i.fromid) 
 NOT IN (SELECT i2.fromid, i2.toid FROM inbox AS i2 WHERE i2.time >= i.time) 
GROUP BY i.fromid
ORDER BY lastmsg DESC;