I have tables that look like this:
create table users (
user_id uuid,
user_name varchar(32)
);
create table messages (
message_id uuid,
from_id uuid references users(user_id),
to_id uuid references users(user_id),
the_message varchar(140),
primary key(message_id)
);
If I do the following:
select * from messages
I will be given UUIDs. I want to display the users.user_name for the given uuid. This gets me close:
select
users.user_name as from_id,
users.user_name as to_id
from messages
join users on users.user_id = messages.from_id
;
The result displays the same user for both the “from” and the “to” field.
How do I display the user_name for the from_id, and also the user_name for the to_id?
You need to
JOINthe users table twice — once for the from user and once for the to user: