sql - Mysql Query combine two colums and get unique values of both -


i can't figure out how following.

what have

... mysql table "mails" like:

id | sender | recipient | date                 | content | read --------------------------------------------------------------- 1  | 3      | 2         | 2016-07-29 09:04:21  | hello   | 1 2  | 2      | 3         | 2016-07-29 09:14:21  | hello   | 1 3  | 1      | 2         | 2016-07-29 09:24:21  | hello   | 1 4  | 1      | 3         | 2016-07-29 09:34:21  | hello   | 0 5  | 1      | 1         | 2016-07-29 09:44:21  | hello   | 1 6  | 3      | 1         | 2016-07-29 09:54:21  | hello   | 0 7  | 1      | 1         | 2016-07-29 09:56:21  | hello   | 1 8  | 1      | 3         | 2016-07-29 09:58:21  | hello   | 0 9  | 2      | 2         | 2016-07-29 09:59:21  | hello   | 0 

what need

... overview of latest chatpartners 1 person, user id 1 (the user can send messages himself) like

date                | partner 2016-07-29 09:58:21 | 3 2016-07-29 09:56:21 | 1 2016-07-29 09:24:21 | 2 

no matter if user recipient or sender , no matter how many messages have been send or received. (i included date column in example output clarify need them sorted date desc, not need included in final result)

what tried

select distinct sender,recipient mails recipient=1 or sender=1 order date desc 

but of course not combine 2 columns. output is

sender | recipient 1      | 3 1      | 1 3      | 1 1      | 2 

if add group sender not display mails user 1 recipient.

i tried following

select     max(date) d,     concat(greatest(sender,recipient),"_",least(sender,recipient)) p mails recipient=1 or sender=1 group p order d desc 

which, example, gives

d                   | p 2016-07-29 09:58:21 | 3_1 2016-07-29 09:56:21 | 1_1 2016-07-29 09:24:21 | 2_1 

what seems great, can take first id shown ... when user id 2, gives

d                   | p 2016-07-29 09:59:21 | 2_2 2016-07-29 09:24:21 | 2_1 2016-07-29 09:14:21 | 3_2 

... unclear if first or second id partner's id.

result

i'm kind of desperate. great.

i think want aggregation this:

select max(date) date,        (case when m.recipient = 1 m.sender else m.recipient end) partner mails 1 in (m.recipient, m.sender) group (case when m.recipient = 1 m.sender else m.recipient end) order max(date); 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -