这段代码:
SELECT m.message,
MAX(m.time) AS time,
m.sender,
m.receiver,
m.contact,
u.ufirstname
FROM( (SELECT message,
receiver_uid AS receiver,
sender_uid AS sender,
time,
receiver_uid AS contact
FROM messages
WHERE sender_uid = '$me' )
UNION
(SELECT message,
receiver_uid AS receiver,
sender_uid AS sender,
time,
sender_uid AS contact
FROM messages
WHERE receiver_uid = '$me' ) ) AS m,
users AS u
WHERE m.contact = u.uid
GROUP BY m.contact
ORDER BY time DESC;
我的问题是这件作品应该选择对话的最新消息。 这是数据库的格式:
Sender_uid | receiver_uid | message | time («What format should this be?)
第一部分检索“$ me”(=登录用户的用户ID)参与的所有消息。所以所有消息是'$ me'是发送还是接收。 第二部分应选择每个'对话'的最近时间(最高值)(=联系人ID,无论联系人是接收者还是发送者)
不获取最新消息。 确实会给您一条来自对话的消息。
重要提示(?):我认为该脚本正在检索最近的消息,其中'$ me'是发件人。
我希望它收集最后一条消息,无论我是接收者还是发送者。
答案 0 :(得分:1)
请停止滥用MySQL混合聚合和非聚合。虽然MySQL允许它,但是每个列的记录都是不可预测的,它们甚至不必来自同一条记录(同步)
SELECT m2.message,
m2.time AS time,
m2.sender,
m2.receiver,
m.contact,
u.ufirstname
FROM (
SELECT
case when sender_uid = '$me' then receiver_uid else sender_uid end Contact,
max(time) maxtime
FROM messages
WHERE sender_uid = '$me' or receiver_uid = '$me'
group by case when sender_uid = '$me' then receiver_uid else sender_uid end
) AS m
INNER JOIN messages m2 on m.maxtime = m2.time
and ((m2.sender_uid = '$me' and m2.receiver_uid = m.Contact)
or
(m2.receiver_uid = '$me' and m2.sender_uid = m.Contact))
INNER JOIN users AS u on m.contact = u.uid
ORDER BY time DESC;
@updated查询 - 看起来更复杂。