我正在尝试编写一个涉及两个表的简单查询。 “人物”表格具有唯一的person_id
和name
,“朋友”表格中包含person_id
和friend_id
,这是{{1}的FK在人员表中。
person_id
我想选择所有人1的朋友的名字。
我可以使用person:
<PK> int person_id
varchar[45] name
friends:
<PK> int person_id
<PK> int friend_id
语句轻松完成此操作:
IN
但是,我并不擅长撰写SELECT p.name FROM person p WHERE p.person_id IN (SELECT f.friend_id FROM friends f WHERE f.person_id = 1);
陈述。有人可以帮我写等效的连接吗?
显然这是一个人为的例子,但我尝试过我的真实数据并且在概念上遗漏了一些东西。感谢。
答案 0 :(得分:7)
你想要这样的东西:
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的名字)
答案 1 :(得分:6)
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 = <your criteria>
答案 2 :(得分:1)
SELECT p.name FROM person p
INNER JOIN friends f ON f.friend_id = p.person_id
WHERE f.person_id = 1;
答案 3 :(得分:0)
select p.name from person p, friends f where f.friend_id = p.person_id and f.person_id = 1
答案 4 :(得分:0)
我很确定托尼·安德鲁斯说得对,除了我认为正确的语法将源表放在左边,连接表放在右边......
SELECT p.name FROM person p
INNER JOIN friends f ON p.person_id = f.friend_id
WHERE f.person_id = 1
这将返回在[person.name]
字段中找到[person.person_id]
值并且[friends.friend_id]
字段等于1的所有记录的[friends.person_id]
字段....是[1]的朋友,当它们被连接在一起并且仅限于friends.person_id=[1]