需要sql select语句

时间:2015-05-28 06:56:04

标签: sql oracle

我的数据库中有以下表结构。

  Table User
      --------------
      UserID EmailAddress Password Gender DOB      Location
      ------------------------------------------------------
      1      bob@bob.com  bobbie   M      1/1/2009 New York City
      2      jon@jon.com  jonathan M      2/2/2008 Los Angeles
      3      joe@joe.com  joseph   M      1/2/2007 Pittsburgh


      Table Friends
      ---------------
      UserID FriendID
      ----------------
      1      2
      1      3
      2      3

这将显示Bob is friends with both Jon and JoeJon is also friends with Joe

在这个例子中,我们假设友谊总是两种方式,所以你不需要表格中的一行,例如(2,1) or (3,2),因为它们已经在另一个方向上表示。

现在我需要查询来检索jon的朋友名称。

1 个答案:

答案 0 :(得分:1)

SELECT UserName -- or any other field you want about the friend
FROM User
WHERE 
   UserID IN(
     SELECT FriendID
     FROM Friends
     WHERE
        UserID = 2) -- Assuming 2 is the UserID of Jon.
OR
    UserID IN(
       SELECT UserID
       FROM Friends
       WHERE 
         FriendID = 2) -- to include the other way around.