3

I have a table called sk_messages.It's structure is like the following:

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.

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
3
  • Foreach msg_from_user_id which message you want to get? the latest the first? Commented Feb 13, 2013 at 9:14
  • @MahmoudGamal The latest message from that person Commented Feb 13, 2013 at 9:15
  • use group function on user_id column Commented Feb 13, 2013 at 9:16

3 Answers 3

6

Try to group user by id.

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 '
Sign up to request clarification or add additional context in comments.

4 Comments

@Dinesh Parmer I have tried to accept your answer,but it says i should wait for some more minutes.now it says about 4 minutes.After that i will accept your answer.I have already upvoted your answer
@Dinesh Parmar Oh sure.I have a little problem more.I am not getting the latest message from that particular user..
use ORDER BY msg_date DESC
3

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;

SQL Fiddle Demo

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.