sql查询获取所有发送和接收的聊天并获取最后发送的消息。 目前,我有这样的办公室。但是在接收者回应之前不会返回我发送的消息。
SELECT DISTINCT
chat.`from`,
chat.`to`,
chat.`message`,
chat.`sent`,
usuarios.`usuario`,
usuarios.`avatar`
FROM
chat,
usuarios
WHERE
(chat.`to` = 'user')
AND chat.`from` = usuarios.usuario
GROUP BY
chat.`from`
ORDER BY
chat.sent,
chat.message ASC
我的数据库看起来像
| id | int(10) unsigned
| from | varchar(255)
| to | varchar(255)
| message | text
| sent | datetime
| recd | int(10) unsigned
答案 0 :(得分:1)
我认为你错过了第二个条件
(SELECT DISTINCT
chat.`from`,
chat.`to`,
chat.`message`,
chat.`sent`,
usuarios.`usuario`,
usuarios.`avatar`
FROM
chat,
usuarios
WHERE
chat.`to` = 'user' AND chat.`from` = usuarios.usuario
GROUP BY
chat.`from`
ORDER BY
chat.sent,
chat.message ASC)
UNION
(SELECT DISTINCT
chat.`from`,
chat.`to`,
chat.`message`,
chat.`sent`,
usuarios.`usuario`,
usuarios.`avatar`
FROM
chat,
usuarios
WHERE
chat.`from` = 'user' AND chat.`to` = usuarios.usuario
GROUP BY
chat.`from`
ORDER BY
chat.sent,
chat.message ASC)
答案 1 :(得分:0)
可以将您的查询更新为:
SELECT DISTINCT
chat.`from`,
chat.`to`,
chat.`message`,
chat.`sent`,
u1.`avatar`,
u2.`avatar`
FROM
chat
inner join usuarios as u1 on chat.`from` = u1.usuario
inner join usuarios as u2 on chat.`to` = u2.usuario
WHERE
chat.`to` = 'user'
AND chat.`from` = 'user'
GROUP BY
chat.`from`
ORDER BY
chat.sent,
chat.message ASC