我有一个消息页面,我只需要从每个用户获取最后一条消息,我的数据库如下:msg_id,message,userid,toid,datecreated 它用于php聊天,我只需要每个用户的最后一条消息
我以这种方式获得结果
<?php
$sqlmessages = mysql_query("SELECT * FROM messages WHERE toid=$logid");
while($runrows = mysql_fetch_assoc($sqlmessages))
{
$aid = $_POST ['m_id'];
$message = $runrows ['message'];
$userid = $runrows ['uid'];
$toid = $runrows ['toid'];
$date = $runrows ['datecreated'];
?>
<?php echo $message;?>
<?php } ?>
我需要更改sql以获取来自数据库的最后一条消息,任何想法?
答案 0 :(得分:1)
试试这个:
$sqlmessages = mysql_query("SELECT * FROM messages WHERE toid=$logid ORDER BY msg_id DESC LIMIT 1");
修改强>
然后这样做:
$sqlmessages = mysql_query("SELECT * FROM messages WHERE toid=$logid GROUP BY(userid) ORDER BY msg_id DESC");
答案 1 :(得分:0)
试试这个:我假设$userid
是您用户的字段
$query = "SELECT * FROM messages WHERE toid=$logid GROUP BY $userid ORDER BY $date DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['$userid']. " - $". $row['$message'];
echo "<br />";
}
答案 2 :(得分:0)
集思考:
SELECT
u.user_name,
u.uid,
m.m_id,
m.toid,
m.datecreated
FROM
users u
LEFT JOIN
/* auxilary table to create set of uid with max m_id*/
(SELECT
uid,
MAX(m_id) max_id
FROM
messages
GROUP BY uid
) a
ON u.uid = a.m_id
LEFT JOIN
/* now join the messages again to get the latest message */
messages m
ON a.uid = m.uid AND a.m_id = m.m_id
如果只需要有消息的用户在INNER join
中更改LEFT