在sql中我已经列出了我需要的数据。我需要得到以下内容,我需要在第一个地方(就像在电子邮件中一样)和其他具有相同message_id的条目下面的所有消息的最后一个条目具有相同的message_id。
它应该在示例中,但显然在两组结果中。
...的DDL
CREATE TABLE `messages` (
`id` INT(5),
`from` VARCHAR(20),
`messages` VARCHAR(200),
`to` VARCHAR(20),
`message_id` INT(3)
) DEFAULT CHARSET=utf8;
INSERT INTO `messages` (`id`, `from`, `messages`, `to`, `message_id`) VALUES
(1, 'Andy', 'First message', 'Jack', '1'),
(2, 'Jack', 'First message reply 1', 'Andy', '1'),
(3, 'Andy', 'First message reply 2', 'Jack', '1'),
(4, 'Jack', 'First message reply 3', 'Andy', '1'),
(5, 'Andy', 'Second message', 'Jack', '2'),
(6, 'Jack', 'Second message reply 1', 'Andy', '2'),
(7, 'Jack', 'Second message reply 2', 'Andy', '2');
sqlfiddle.com /#!2 / f36f5 / 7
我想我需要一种双sql语句,其中第一个接收最新消息,第二个接收所有其他消息。
或许我需要第二张表来做这件事。
答案 0 :(得分:0)
根据我的理解,您想要的结果应如下所示:
"4","Jack","First message reply 3","Andy","1"
"3","Andy","First message reply 2","Jack","1"
"2","Jack","First message reply 1","Andy","1"
"1","Andy","First message","Jack","1"
"7","Jack","Second message reply 2","Andy","2"
"6","Jack","Second message reply 1","Andy","2"
"5","Andy","Second message","Jack","2"
要在一个查询中获得此结果:
SELECT *
FROM `messages`
ORDER BY message_id, id DESC
在前端,您可以遍历行以打印/显示它们。每当一行开头时,message_id与前一行的message_id不匹配,您就会知道这里有一条新消息。因此,您可以使用该行显示属于该消息的最新条目。只要它们具有相同的message_id,其余部分就可以打印/显示。希望它有所帮助。
答案 1 :(得分:0)
看看this fiddle。我相信这是你追求的结果。要使用PHP处理结果,请尝试以下方法:
/*
First we create a nested array with messages grouped by their message_id
The first few rows will be:
$emails[1][0] = From Andy To Jack, First message
$emails[1][1] = From Jack to Andy, First message reply 1
and so on until
$emails[2][0] = From Andy to Jack, Second message
*/
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$emails[$row['message_id']][] = $row;
}
//Uncomment this line if you want to print the structure of the array. It helps to view source on the results.
//var_dump($emails);
//this foreach loop will run twice, providing a div for each set of messages.
foreach ($emails as $email) {
echo '<div class="Email_thread">';
//this foreach loop will run for each message with a given message_id
//swap in different HTML as needed.
foreach ($email as $message) {
echo 'ID = '.$message['id'].'<br/>';
echo 'From = '.$message['from'].'<br/>';
echo 'To = '.$message['to'].'<br/>';
echo 'Message = '.$message['message'].'<br/>';
echo 'Message_ID = '.$message['message_id'].'<br/>';
}
echo '</div>';
}