使用order by和group by连接表

时间:2013-07-23 13:49:23

标签: mysql database database-schema

SELECT * FROM(
SELECT c_id, user_id, message, state, time FROM message 
WHERE receive=1 
ORDER BY message_id DESC
)AS t GROUP BY c_id

我有mysql语句可以为用户提取最后一条消息。

但是我需要加入用户表,所以我可以取出发件人的名字

LEFT JOIN user ON user.user_id=message.user_id

如何实现这一目标?

//user
user_id name

//conversation
c_id    user_id

//message
m_id    c_id    user_id(sender) receive message state   time

1 个答案:

答案 0 :(得分:1)

SELECT * FROM (
    SELECT c_id, user_id, message, state, time 
    FROM message 
    WHERE receive=1 
    ORDER BY message_id DESC) AS t 
LEFT JOIN user ON user.user_id=t.user_id 
GROUP BY c_id

P.S。检查user.user_id是否存在。