1

I want to generate a thread-like view

In the table I have from,to,date and some other columns

I want to output the rows grouped by from AND to

example data in DB

from,to,date
a,b,somedate
a,c,somedate
b,a,somedate

Query:

SELECT 
    from, to, date 
FROM 
    data 
GROUP BY 
    from, to 
ORDER BY 
    date DESC;

The output I expect is like this: (where from and to is grouped together)

a,b,somedate
a,c,somedate

(b,a,somedate not shows because its in the a,b group) 

but it doesn't ..

The general idea is to have a Messaging View "by user" .. where the list is sorted by recipients,date (not by message) ...

2
  • So you are associating a,b and b,a? Commented Aug 28, 2011 at 8:48
  • Yes correct like the from and to collum to handled as one for the grouping .. (somethings like that) Commented Aug 28, 2011 at 8:59

1 Answer 1

4

If you want one row returned for every (from, to) combination:

SELECT one, two, MIN(somedate) 
FROM
( SELECT `from` AS one, `to` AS two, somedate 
  FROM data 
  WHERE `from` <= `to`
UNION ALL
  SELECT `to`, `from`, somedate 
  FROM data 
  WHERE `from` > `to`
) AS tmp
GROUP BY one
       , two
ORDER BY one
       , two

or, if you want all records:

SELECT one, two, somedate 
FROM
( SELECT `from` AS one, `to` AS two, somedate 
  FROM data 
  WHERE `from` <= `to`
UNION ALL
  SELECT `to`, `from`, somedate 
  FROM data 
  WHERE `from` > `to`
) AS tmp
ORDER BY one
       , two
Sign up to request clarification or add additional context in comments.

2 Comments

i managed to get the message out like this codeSELECT * FROM maili where from='$user' or to='$user' GROUP BY GREATEST(to, from), LEAST(to, from) ORDER BY sent``code the output seems correct but i not get the last message body
@Nullx8: so you want only the latest record for every (from,to) combination?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.