[英]Select DISTINCT rows of multiple columns in mysql
I have a table called sk_messages
.It's structure is like the following: 我有一个名为
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
My requirement is that I want to display all messages which are for the current user with a condition that single message should be displayed from a sender even if he sends multiple messages with the status unread.That is,from the above context, single message of the user having ID 12, should be displayed.I have tried the following query,but it doesnt work. 我的要求是我想要显示当前用户的所有消息,条件是发送者应该显示单个消息,即使他发送了多条状态为未读的消息。也就是说,从上面的上下文中,单个消息应该显示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
Try to group
user by id. 尝试按ID
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
Tested code to get latest message 测试代码以获取最新消息
'SELECT * FROM ( SELECT * FROM message WHERE user_id = 1 ORDER BY created DESC LIMIT 1) as msg GROUP BY user_id '
Try this instead: 试试这个:
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;
Use this 用这个
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.