我的表格看起来像这样:
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)
);
如果我执行以下操作:
select * from messages
我将获得UUID。我想显示给定uuid的users.user_name。这让我很接近:
select
users.user_name as from_id,
users.user_name as to_id
from messages
join users on users.user_id = messages.from_id
;
结果显示“from”和“to”字段的相同用户。
如何显示from_id的user_name以及to_id的user_name?
答案 0 :(得分:3)
您需要JOIN
两次用户表 - 一次是来自用户,一次是来自用户:
select
messages.*,
f.user_name as from_id,
t.user_name as to_id
from messages
join users f on f.user_id = messages.from_id
join users t on t.user_id = messages.to_id
;