我正在尝试编写一个涉及两个表的简单查询."person"表具有唯一的person_id
和a name
,并且"friends"表具有a person_id
和a friend_id
,其是person_id
人员表中的a的FK .
person:int person_id varchar[45] name friends: int person_id int friend_id
我想选择所有人1的朋友的名字.
我可以使用一个IN
声明轻松地做到这一点:
SELECT p.name FROM person p WHERE p.person_id IN (SELECT f.friend_id FROM friends f WHERE f.person_id = 1);
但是,我并不擅长撰写JOIN
陈述.有人可以帮我写等效的连接吗?
显然这是一个人为的例子,但我尝试过我的真实数据并且在概念上遗漏了一些东西.谢谢.
你想要这样的东西:
SELECT p.name, f.friend_id FROM person AS p INNER JOIN friends AS f ON p.person_id = f.person_id WHERE p.person_id = 1
这使用两个表连接在一起 p.person_id = f.person_id
如果一个人没有朋友,你将不会获得任何行 - 如果你不想这样,那么使用LEFT JOIN,你将获得一行NULL friend_id
.
编辑:如果你想加入朋友回到人:
SELECT p.name AS person_name, friend.name AS friend_name FROM person AS p -- Our person INNER JOIN friends AS f ON p.person_id = f.person_id -- the join table INNER JOIN person AS friend on f.friend_id = friend.id -- Join back on person again WHERE p.person_id = 1
也许你需要为你的应用程序提供这样的3方式连接,但更常见的是你只需要如上所述的双向连接,或者像这样:
SELECT p.name, f.friend_id FROM person AS p INNER JOIN friends AS f ON p.person_id = f.friend_id WHERE f.person_id = 1
这将为您提供所有与person_id 1成为朋友的人的姓名(但不是person_id 1的名字)
select p.name, p2.name as friend_name, from person p inner join friends f on p.person_id = f.person_id inner join person p2 on f.friend_id = p2.person_id -- friends where p.person_id =