0

通过在 PHP 中构建一个使用 API 发送和接收消息的自定义消息传递系统,我很高兴能够重新创建手机。我正在尝试在他们的桌面网站上模拟 Facebook 消息传递中的功能。

[Col 1]               [Col 2]
A list of the         Conversation View.
latest messages
received in order
of Newest to oldest

我对第一列的查询有疑问。

我目前在 MySQL 中有一个具有以下结构的表:

CREATE TABLE IF NOT EXISTS `History` (
  `ID` int(10) NOT NULL AUTO_INCREMENT COMMENT 'MessageID',
  `Sender` varchar(10) NOT NULL,
  `Recipient` varchar(10) NOT NULL,
  `ExtReference` int(20) DEFAULT NULL,
  `Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `Status` varchar(100) NOT NULL,
  `userid` int(3) NOT NULL,
  `Message` longtext NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=609 ;

使用示例日期设置,例如:

INSERT INTO `History` (`ID`, `Sender`, `Recipient`, `ExtReference`, `Date`, `Status`, `userid`, `Message`) VALUES
(1, '0412345678', '0468888888', 33845909, '2013-03-17 04:17:34', '1', 11, 'Just testing....'),
(2, '0412345678', '0400222333', 33845910, '2013-03-17 04:17:35', '1', 11, 'Amazing'),
(3, '0412345678', '0411111111', 33847419, '2013-03-17 04:46:04', '1', 8, 'Nothing here to see'),
(4, '0412345678', '0400222333', 33850155, '2013-03-17 06:31:57', '1', 12, 'Hello there Mr IT Guru :-)'),
(5, '0400222333', '0412345678', 33850179, '2013-03-17 06:33:21', '1', 12, '[Write message here]'),
(6, '0412345678', '0411111111', 33955423, '2013-03-23 01:26:22', '1', 8, 'Hello Charles'),
(7, '0412345678', '0411111111', 33959071, '2013-03-23 03:08:26', '1', 13, 'Sample Message'),
(8, '0400222333', '0412345678', 33964111, '2013-03-23 05:27:51', '1', 13, 'How do I use this system?'),
(9, '0400222333', '0412345678', 34107503, '2013-03-30 03:13:38', '1', 12, 'Is this thing on?'),
(10, '0412345678', '0401411210', 34230869, '2013-03-05 00:18:09', '1', 16, 'Hello')

(在这个例子中,我的号码是:0412345678)。SQL小提琴在这里:http ://sqlfiddle.com/#!2/29197/1/0

我已经研究出如何获取在发件人和收件人列中使用的所有唯一号码的列表:

SELECT DISTINCT `Sender` AS phoneID FROM `History`
UNION
SELECT DISTINCT `Recipient` AS phoneID FROM `History`

但我不知道如何将最新的日期和消息附加到这些数据中。

如果我只关注发送给我或由我发送的消息,我可以通过这两个获得某个地方:

SELECT `ID`, `Sender`, `Recipient`, MAX(`Date`), `Message` FROM History 
GROUP BY Sender
ORDER BY `History`.`Date` DESC

或者

SELECT `ID`, `Sender`, `Recipient`, MAX(`Date`), `Message`, `Status` FROM History 
GROUP BY Recipient
ORDER BY `History`.`Date` DESC

有什么想法吗?如果需要,我可以重新创建历史表布局。

我还需要稍后尝试在联系人表中加入带有人名的电话号码。

谢谢查理

4

1 回答 1

0

可能不是最好的方法,但您可以结合您拥有的两个查询。就像是:

SELECT `ID`, `Sender`, `Recipient`,`Date`,`Message`,`Status` FROM
(
SELECT `ID`, `Sender`, `Recipient`, `Date`, `Message`,`Status` FROM History
  WHERE Sender = "0412345678"
GROUP BY Sender
UNION
SELECT `ID`, `Sender`, `Recipient`, MAX(`Date`), `Message`, `Status` FROM History 
  WHERE Recipient = "0412345678"
GROUP BY Recipient
) res

GROUP BY res.ID
ORDER BY res.Date DESC

请注意,这是针对特定数字的。WHERE如果不需要,您可以删除这些子句。

于 2013-04-09T03:31:11.417 回答