简体   繁体   中英

Select distinct from the table and sort by date

I am trying to built the messaging system and I want to select distinct value from the table and sort by date and also return the read and unread status. My table structure is as id, from_user_id, to_user_id, message, datetime, read . Suppose dummy data are as follows:

id   |   from_user_id  | to_user_id   |  message  |      datetime       | read
1    |          20     |     50       |    hi     |  2016-3-13 06:05:30 | 1
2    |          20     |     50       |    hey     |  2016-3-13 06:15:30 | 0
3    |          30     |     50       |    hi     |  2016-3-14 06:05:30 | 0

Now I want to select distinct from_user_id and sort by date so that I can display the name of the user who is chating recently on top of list and also return the read status 1, if any of the rows with from_user_id has read status 0, then I want to return read as 0 so that I can differentiate whose user message has unread message.

Suppose, from_user_id has read status as 0 in one rows then I want to return read status as 0 when returning distinct value of from_user_id . How can I do it. I tried as follows but won't work in my case. It returns distinct value but not sorted by date and also read status in not returning what I expect.

 select distinct(`from_user_id`),register.name FROM message INNER JOIN register ON register.id = message.from_user_id where message.to_user_id = $user_id GROUP BY message.id ORDER BY MAX(datetime) ASC

Try the following query:

SELECT
message.from_user_id,
register.name,
message.read
FROM message 
INNER JOIN 
(
  SELECT  
   from_user_id,
   MAX(datetime) max_datetime
  FROM message 
  WHERE to_user_id = 50
  GROUP BY from_user_id ) t
 ON t.from_user_id = message.from_user_id AND t.max_datetime = message.datetime
INNER JOIN register ON register.id = message.from_user_id
WHERE message.to_user_id = 50
ORDER BY message.datetime ASC

UPDATED SQL FIDDLE

Sample Input:

id   |   from_user_id  | to_user_id   |  message  |      datetime        | read

1    |          20     |     50       |    hi     |  2016-3-13 06:05:30  | 1
2    |          20     |     50       |    hey    |  2016-3-13 06:15:30  | 0
3    |          30     |     50       |    hi     |  2016-3-14 06:05:30  | 0

Output:

from_user_id        name        read

20                 User20      0
30                 User30      0

Note: This query might give you multiple row for the same from_user_id if there exists multiple entries in your message table having the same datetime and same to_user_id .

checkout this query :

SELECT DISTINCT(form_user_id),MIN(read) FROM table_name ORDER BY datetime ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM