我想检索发送或接收的最后一条消息,该消息与通过AJAX在文本框中输入的用户名相匹配,但我无法编写正确的MySQL查询。
这是我的代码:
$name=$_GET['name'];
$query_get_user_id = "SELECT id from login WHERE email = '".$_SESSION['login_user']."'";
$result_get_userid=$mysqli->query($query_get_user_id);
$user_row = mysqli_fetch_array($result_get_userid);
$user_id=$user_row['id'];
$query_second_user_id = "SELECT id from login WHERE name LIKE '".$name."%'";
$result_second_get_userid=$mysqli->query($query_second_user_id);
$user_second_row = mysqli_fetch_array($result_second_get_userid);
$second_user_id=$user_second_row['id'];
$query_get_all_users ="SELECT DISTINCT sender_id,receiver_id from message WHERE ((sender_id='".$user_id."' AND receiver_id='".$second_user_id."') OR (sender_id='".$user_id."' AND receiver_id='".$second_user_id."')) order by timestamp desc";
$result_get_all_users=$mysqli->query($query_get_all_users);
while($retrieve_user_row = mysqli_fetch_array($result_get_all_users)){
这是我的表结构:
答案 0 :(得分:0)
您可以使用变量根据时间戳对每个用户的消息进行排名,将最新消息排名为1,并仅保留排名为1的消息。
select * from (
select m.*,
@rn := if(u.id = @prevUserId, @rn+1, 1) rn,
@prevUserId := u.id
from users u
join messages m on u.id in (m.sender_id,m.receiver_id)
where u.name like 'name%'
order by u.id, timestamp desc
) t1 where rn = 1
答案 1 :(得分:0)
抱歉,我弄错了,我只为登录用户或一个用户开发了查询,现在我明白了。
请尝试更新此查询。我在本地数据库上进行了测试,并按预期工作。
SELECT *
FROM message mm
INNER JOIN
(SELECT sender, MAX(createdtime) AS MaxDateTime
FROM message
WHERE sender IN
(select id from user where name like 'search_filter%')
GROUP BY sender) groupedmm
ON mm.sender = groupedmm.sender
AND mm.createdtime = groupedmm.MaxDateTime;