开发者

"Friend" relationships across two mysql tables

I'm not quite sure how to construct an sql join inorder to find who a specific users "friends" are.

For example I have two table

User Table
u_ID  | u_Name
-------------
1     |  bob
2     |  jill
3     |  jack
4     |  susan

Friends Table
f_开发者_运维技巧ID | u_ID1 | u_ID2
--------------------
1    |   1   |   2
2    |   3   |   1
3    |   4   |   2

I need to find a way of getting all of bobs friends, or all of jills friends, for example.

Friends cannot have duplicate results

I.e. can have a row with either (u_ID1 = 1, u_ID2 = 2) or (u_ID1 = 2, u_ID = 1) but not both, as they are technically the same.

Here is my incorrect query

SELECT u.u_Name
FROM user u
INNER JOIN friends f ON (f.u_ID1 = '1' OR f.u_ID2 = '1')

Thanks in advance


Solution

Check Kris Babic reply for solution,

also thank you for everyone elses help


This uses a STRAIGHT join, but should work:

select u.u_Name
from friends f, user u
where (f.u_ID1 = '1' and u.u_ID = f.u_ID2) 
  or (f.u_ID2 = '1' and u.u_ID = f.u_ID1)


For all of bob's friends this should work (untested)

select u.u_Name
FROM user u
inner join friends f1 on f1.u_uID1 = u.u_ID
inner join friends f2 on f2.u_uID2 = u.u_ID
where u.u_ID = 1


Try this:

SELECT u1.u_Name as user1 , u2.u_Name as user2
FROM user as u1 INNER JOIN friends ON u1.u_ID=friends.u_ID1 
INNER JOIN user as u2 ON u2.u_ID=friends.u_ID2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜