Mysql在Group By中获取最后一个条目

时间:2014-02-06 04:33:06

标签: php mysql sql

嘿,这是我的MySQL查询

$userid="id of logged in user";

SELECT id, MAX( post_time ) , message, user_name, receiver_id, sender_id
FROM chat
WHERE receiver_id =$userid
OR sender_id =$userid
GROUP BY GREATEST( receiver_id, sender_id ) , LEAST( receiver_id, sender_id ) 
ORDER BY id DESC 
LIMIT 0 , 1000

它给出了两个用户之间记录的第一条消息而不是最后一条消息。因为我想要在消息收件箱中显示最后一条消息。我使用此查询在收件箱中显示与登录用户的不同用户的唯一对话(或者您可以说特定用户) 您可以查看demo @ http://www.funnenjoy.com/home

3 个答案:

答案 0 :(得分:0)

试试这个,

SELECT id, message, user_name, receiver_id, sender_id
FROM chat
WHERE post_time = MAX(post_time) AND (receiver_id =$userid
OR sender_id =$userid)
GROUP BY GREATEST( receiver_id, sender_id ) , LEAST( receiver_id, sender_id ) 
ORDER BY id DESC 
LIMIT 0 , 1000

答案 1 :(得分:0)

这可能对您有所帮助

SELECT id, message, user_name, receiver_id, sender_id
FROM chat
WHERE receiver_id =$userid
OR sender_id =$userid
HAVING post_time = MAX(post_time) 
GROUP BY GREATEST( receiver_id, sender_id ) ,         LEAST( receiver_id, sender_id ) 
ORDER BY id DESC 
LIMIT 0 , 1000

答案 2 :(得分:0)

我的代码由我解决了.............如果任何人需要它也会帮助别人而不是

SELECT m.* 
FROM (
SELECT sender_id + receiver_id -1 AS other_recipient_id, MAX( id ) AS id
FROM chat
WHERE (sender_id =*user's_id*
OR receiver_id =*user's_id*)
GROUP BY sender_id + receiver_id -1
)mm
INNER JOIN chat m ON mm.id = m.id
ORDER BY id ASC