简体   繁体   English

SQL中具有2个表且无重复的双向关系

[英]Two way relationship in SQL with 2 tables and no duplicates

Assuming you have 2 tables: user and friends - you want to join all friends to the user you query. 假设您有2个表: userfriends您想将所有朋友加入您查询的用户。

The obvious answer is: 显而易见的答案是:

SELECT friend.uid
FROM `user`
JOIN friends ON user.uid = friends.user
JOIN user AS friend ON friends.friend = friend.uid
WHERE user.uid = $user_id

This works fine but it's a one-way relationship. 这很好用,但是是单向关系。 To make this work I'd have to add 2 rows for every relationship. 为了完成这项工作,我必须为每个关系添加2行。

On the other hand, this works both ways: 另一方面,这两种方法都起作用:

SELECT friend.uid
FROM `user` 
JOIN friends ON user.uid IN(friends.col1, friends.col2)
JOIN user AS friend ON
  friend.uid IN(friends.col1, friends.col2)
WHERE user.uid = $user_id AND friend.uid != user.uid

But this is makes use of multiple IN() s is not very clean and probably comes with a big performance hit. 但这是因为使用多个IN()并不是很干净,并且可能会对性能产生重大影响。

Are there any other ways to do this? 还有其他方法吗?

You simply use UNION ALL and skip the join entirely, something like; 您只需使用UNION ALL并完全跳过联接,就像;

SELECT friends.col1 friend_uid FROM friends WHERE friends.col2 = $user_id
UNION ALL
SELECT friends.col2            FROM friends WHERE friends.col1 = $user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM