我有一个用户列表和一个联结表,其中两个字段都是user_id
,代表友谊。
所以数据库是
id | name
----------------------
1 Julia
2 Davos
3 Michael
4 Anthony
user1_id | user2_id
--------------------------
3 1
2 4
我想选择友谊列表,例如
Michael | Julia
Davos | Anthony
但这一次只是让我感到非常难过,谷歌也没有帮助。有人可以提供小费吗?
答案 0 :(得分:1)
要获取该信息,您应该使用像pivot这样的友谊连接两次到用户表
SELECT friend_1.name,friend_2.name
FROM friendships AS relation_friend
JOIN users AS friend_1 ON friend_1.id=relation_friend.user1_id
JOIN users AS friend_2 ON friend_1.id=relation_friend.user1_id;
问候。
答案 1 :(得分:1)
它可以动态地处理任意数量的数据:
select tbl.name, tb2.name from
(select *
from
users as a
inner join
friendships as b
on a.id=b.user1_id
or a.id=b.user2_id) as tbl
inner join
(select *
from
users as a
inner join
friendships as b
on a.id=b.user1_id
or a.id=b.user2_id) as tb2
on tbl.user2_id=tb2.id
where tbl.name <> tb2.name