2014-07-26 76 views
0

加入的3表我有以下3个表:UsersFriendship & LocationSQL基于两列

我需要写的查询,其中通过数据从基于用户标识的所有3台拉。

enter image description here

enter image description here

我觉得这里的技巧是,你必须根据从友谊表,即用户名和friendid两列(所以无论是对方的朋友)来提取数据,并在此基础上用户的朋友列表你需要,你需要相应地拉他的朋友的名字,电子邮件和位置。

我已经写了一些查询使用连接,但不能得到我需要如上所述。

任何帮助将非常感激。

+0

嘿,你的问题和我的一样吗? :http://stackoverflow.com/questions/25015124/datatables-searching-at-server-side-php-mysql ..你有解决方案吗? – user3209031

回答

1
select f.id as friendshipid, 
     f.userid, 
     f.friendid, 
     u.name, 
     u.email, 
     l.location 
    from (select id, userid, friendid 
      from friendship 
     union all 
     select id, friendid, userid 
      from friendship) f 
    left join location l 
    on f.friendid = l.userid 
    left join users u 
    on f.friendid = u.id 
where f.userid = 2 

这里你可以看到一个小提琴测试:http://sqlfiddle.com/#!6/8eba4/13/0

我用反转友谊表,并连接回表本身与工会线视图,这样的查询看到的友谊在两个方向,因为它们只存储在一个方向上。

+0

非常感谢Brian的快速反应。 我已经走了很远,不幸的是这不适合我。 如果我喂用户ID = 1以上查询工作完美。 如果我提供userid = 2,则不返回任何内容。 –

+0

@Mubi先生我相信我已经修复了它,请参阅新的小提琴和sql。 –

+0

@Brain再次感谢,我已经尝试过。对于userid = 1和2,它会得到相同的结果。所以基本上第一个查询对于userid = 1工作正常,对于userid = 2工作正常。我需要两个工作正常的查询。或者可能有限制,需要更改db的结构。但我想知道是否有解决方案如何将朋友列表保存在数据库中。我不觉得有一个友谊的2条记录是合适的。就好像用户jim向jay发送请求并且都是朋友一样,它应该保存在单个记录中?有什么想法吗? –

0

如果您一次只提取一个ID,则可以在不进行子查询的情况下执行此操作。

SELECT friendship.id FriendshipID 
, @SearchedID UserID 
, users.id FriendID 
, users.name Name 
, users.email Email 
, location.location Location 
FROM friendship 
INNER JOIN users 
    ON friendship.userid = users.id 
    OR friendship.friendid = users.id 
INNER JOIN location 
    ON users.id = location.userid 
WHERE 
    users.id <> @SearchedID 
    AND (friendship.userid = @SearchedID OR friendship.friendid = @SearchedID);