This sounds simple, and probably is…
Alright, so I have two tables, users and messages.
Formatted like so:
users
ID | username
1 | im_a_user
2 | another_user
messages
ID | FROM | TO | CONTENT
1 | 1 | 2 | Blah blah blah...
2 | 2 | 1 | Hello, World!
3 | 2 | 1 | Another message.
If you didn’t guess, columns FROM and TO are references to the ID from the table users.
Anyhow, I’d like to make a query that returns something like this:
ID | FROM | TO | CONTENT
1 | im_a_user | another_user | Blah blah blah...
2 | another_user | im_a_user | Hello, World!
3 | another_user | im_a_user | Another message.
I’ve done this before with JOINS, but I’m a bit rusty, and I was wondering if there was a simpler way.. If not, a query using a JOIN is fine.
JOINs exist exactly for things like that. You need a query like this:If you have
NULLs on columnsTOorFROM, change the apropriateINNER JOINto aLEFT OUTER JOIN.As a side note, I’d recommend you refrain from using SQL reserved words such as
FROMas column names.