我正在进行Facebook风格的聊天,并尝试从一个用户获得与其他用户的所有最新对话。 现在我正在收到所有最新的对话,但是在其他用户写信给我的情况下。我想要做的是例如我有2个对话,对话1是我写的最新内容,但现在我写入对话2,当我刷新页面时,对话2将是第一个。 现在,如果对话1的另一个人写信给我,如果我刷新页面会话1将是第一个。 这是我正在使用的两个表:
CREATE TABLE users (
id int(255) not null auto_increment,
username varchar(150) null,
email varchar(150) null,
password varchar(255) null,
salt varchar(255) null,
pic varchar(255) not null,
primary key(id)
) ENGINE = INNODB DEFAULT CHARSET=utf8;
CREATE TABLE chat (
id int(255) not null auto_increment,
id_us int(255) not null,
id_receptor int(255) not null,
message varchar(3000) not null,
chat_date datetime not null,
primary key (id),
index chatUsId(id_us),
index chatRecId(id_receptor),
foreign key (id_us) references users(id) on delete cascade,
foreign key (id_receptor) references users(id) on delete cascade
) ENGINE = INNODB DEFAULT CHARSET=utf8;
这是我正在使用的查询
SELECT m.id_us, m.id_receptor, u.username, u.pic
FROM users AS u, chat AS m
WHERE (m.id_us = u.id AND m.id_receptor =:id_us or m.id_receptor = u.id AND m.id_us =:id_us)
AND m.chat_date = (SELECT MAX( c.chat_date ) FROM chat AS c WHERE m.id_us = c.id_us AND m.id_receptor = c.id_receptor )
group by u.username
ORDER BY m.id DESC
在这种情况下:id_us可以是例如1 我知道它不正确,因为它没有做我想做的事情,但是我一直在努力寻找获得我想要的结果的方法,但我被困住了,任何帮助都会被贬低。 为了更好地解释自己,我想要做的是例如当您在Facebook聊天时,在Facebook消息列表中查看您的最新对话。
答案 0 :(得分:1)
确定如何:(对于user1的id使用123)
select T1.user2_id, users.username, users.pic, max(cdate) maxDate from
(select chat.id_receptor user2_id, max(chat_date) cdate
from chat
where chat.id_us=123
group by chat.id_receptor
union distinct
(select chat.id_us user2_id, max(chat_date) cdate
from chat where chat.id_receptor = 123
group by chat.id_us)) T1
inner join users on (users.id = T1.user2_id)
group by T1.user2_id
order by maxDate desc
答案 1 :(得分:0)
我希望最近的消息也像whatsapp一样,我根据我的表格更新了你的查询。
date
答案 2 :(得分:0)
刚刚添加了另一个SELECT + JOIN。请参考下面的内容,如果有任何问题请与我们联系,我们将尽力回答。
我想请注意,即使上面的答案被标记是正确的,但据我所知,它并不涵盖所请求查询的全部需求,因为不显示关键项 - 即每次聊天的最后一条消息。
$sql="
SELECT T2.maxDate, T2.user2_id, T2.ava, T2.userName,chat.user_to,chat.user_from,chat.body,chat.viewed FROM (SELECT T1.user2_id, users.userName, users.ava, max(cdate) maxDate FROM
(SELECT chat.user_to user2_id, max(msg_time) cdate
FROM chat WHERE chat.user_from=18
GROUP BY chat.user_to
union distinct
(SELECT chat.user_from user2_id, max(msg_time) cdate
FROM chat WHERE chat.user_to=18
GROUP BY chat.user_from)) T1
inner join users on (users.userID = T1.user2_id)
group by T1.user2_id
order by maxDate desc) T2
join chat on (T2.maxDate = chat.msg_time) ORDER BY T2.maxDate DESC";