我有一个名为sk_messages
的表。它的结构如下:
msg_id msg_from_user_id msg_to_user_id msg_text msg_date msg_status
1 12 14 hai... 23-12-2013 unread
2 12 14 .... ... unread
3 13 14 ... .. unread
我的要求是我想要显示当前用户的所有消息,条件是发送者应该显示单个消息,即使他发送了多条状态为未读的消息。也就是说,从上面的上下文来看,应该显示具有ID 12的用户的单个消息。我已经尝试了以下查询,但它不起作用。
SELECT DISTINCT (msg_from_user_id), msg_text, msg_date
FROM sk_messages
WHERE msg_to_user_id = '$user_id'
AND msg_status = 'unread'
ORDER BY msg_date
$user_id is the id of the login user
答案 0 :(得分:6)
尝试按group
用户身份。
SELECT msg_text, msg_date
FROM sk_messages
WHERE msg_to_user_id = '$user_id'
AND msg_status = 'unread'
GROUP BY msg_from_user_id
ORDER BY msg_date
经过测试的代码以获取最新消息
'SELECT * FROM ( SELECT * FROM message WHERE user_id = 1 ORDER BY created DESC LIMIT 1) as msg GROUP BY user_id '
答案 1 :(得分:3)
请改为尝试:
SELECT
m1.msg_from_user_id,
m1.msg_text,
m1.msg_date
FROM sk_messages AS m1
INNER JOIN
(
SELECT msg_from_user_id, MAX(msg_date) AS LatestDate
FROM sk_messages
WHERE msg_to_user_id = '$user_id'
AND msg_status = 'unread'
GROUP BY msg_from_user_id
) AS m2 ON m1.msg_from_user_id = m2.msg_from_user_id
AND m1.msg_date = m2.LatestDate
ORDER BY m1.msg_date;
答案 2 :(得分:0)
使用此
SELECT msg_from_user_id,
msg_text, msg_date
FROM sk_messages
WHERE msg_to_user_id = '$user_id'
AND msg_status = 'unread'
ORDER BY msg_date GROUP BY msg_from_user_id