我有4张桌子:
会话结构表是:
conversations_users结构表是:
消息结构表是:
用户结构表是:
我想显示用户的所有会话(标题,最后消息和上次消息时间戳),以便只显示用户所在的会话。
如何处理SQL请求?我猜它会是这样的:
SELECT c.title, m.message, m.date
FROM conversation c
INNER JOIN conversation_users cu
ON ...
INNER JOIN messages m
ON ...
INNER JOIN users u
ON ...
GROUP BY u.id
答案 0 :(得分:1)
select usr.userID,
cvs.title,
msg.message,
times.date
from conversations_users usr
left join conversations cvs on usr.conversationID = cvs.id
left join messages msg on usr.conversationID = msg.conversationID
left join
(select usr.userID,
MAX(msg.date) as date
from conversations_users usr
left join messages msg on usr.conversationID = msg.conversationID
group by usr.userID) times on times.userID= usr.userID and times.date=msg.date