sql - MySQL join with two potential field names -


for website i'm working on tasked implementing private messaging system. basic scenario here is, there several message entries in database, each containing sender , recipient. however, "current user" should able see both messages, both relevant him. problem is, interested in data of other user, not own. "current user" can both sender or recipient.

my query down here gets job done, hardly elegant. joining both users, deciding using if data should get.

select     if(m.sender = ?, 1, 0) isself,     if(m.sender = ?, u_recipient.id, u_sender.id) other_id,     if(m.sender = ?, u_recipient.displayname, u_sender.displayname) other_name,     if(m.sender = ?, u_recipient_avatar.url, u_sender_avatar.url) other_avatar,     m.text text messages m     left join user u_sender         on u_sender.id = m.sender     left join avatars u_sender_avatar         on u_sender_avatar.id = u_sender.avatarid      left join user u_recipient         on u_recipient.id = m.recipient     left join avatars u_recipient_avatar         on u_recipient_avatar.id = u_recipient.avatarid ( m.sender = ? or m.recipient = ? )     , unix_timestamp(m.timestamp) > ? order m.timestamp asc limit 100 

so basically, question here is, there more elegant way of doing this? storing sender/recipient int 1 single table reused in join? otherwise, performance hog (joining tables don't need?). or should take care of seperating these in application itself?

thanks in advance!

seeing not allowed edit other answer, partially correct. answer here based on ben's, however, syntax errors removed.

select d.isself, other_id, u.displayname other_name, a.url other_avatar, text (     select 0 isself, m.sender other_id, m.timestamp, m.text     messages m     m.recipient = ?      union      select 1 isself, m.recipient other_id, m.timestamp, m.text     messages m     m.sender = ? ) d     left join user u          on u.id = d.other_id     left join avatars         on a.id = u.avatarid unix_timestamp(timestamp) > ? order m.timestamp asc limit 100 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -