2017-02-14 78 views
3

这里是我的表结构:如何限制选择只有具有共同价值的行?

// users 
+----+--------+ 
| id | name | 
+----+--------+ 
| 1 | Jack | 
| 2 | Peter | 
| 3 | John | 
| 4 | Barman | 
| 5 | Ali | 
+----+--------+ 

// friends 
+---------+-----------+ 
| user_id | friend_id | 
+---------+-----------+ 
| 1  | 3   | 
| 1  | 4   | 
| 1  | 5   | 
| 3  | 1   | 
| 3  | 2   | 
| 3  | 4   | 
| 5  | 2   | 
+---------+-----------+ 

-- both user_id and friend_id columns refer to the id column of users table 

这里是我的查询:

// $id = 1; 
select distinct f1.user_id, f1.friend_id 
from friend f1 
where user_id = $id 
     or 
     user_id in (select f2.friend_id 
        from friend f2 
        where user_id = $id); 
/* output 
| 1  | 3   | 
| 1  | 4   | 
| 1  | 5   | 
| 3  | 2   | 
| 3  | 4   | 
| 5  | 2   | 

正如你看到的,我的查询选择

  • Jack(因为$id = 1
  • 全部Jack的好友
  • Jack的朋友

好了所有罚款所有的朋友。实际上,我试图对结果做一个图表。其实我做到了。现在我想限制结果只有常见的朋友。我的意思是我想删除单节点。换句话说,我想选择至少有两条边的朋友

通过更改查询或者我应该在PHP图层中这样做可能吗?


视觉例子,它的预期输出:

enter image description here

+0

添加SELECT COUNT条件在第二个'选择..'应该做的工作。 – kawadhiya21

+0

更新您的问题,并添加您的选择和预期结果的实际结果..(根据您的数据样本) – scaisEdge

+0

@scaisEdge预期输出添加。 – stack

回答

0

波纹管查询将返回所有常见的朋友说,不是直接的朋友:

select distinct f.user_id, f2.friend_id common_friend 
from friends f 
inner join friends f2 
     on f.friend_id = f2.user_id 
left join friends f3 
     on f.user_id = f3.user_id 
     and f2.friend_id = f3.friend_id 
where f3.user_id is null 
and f.user_id <> f2.friend_id 
#and f.user_id = 1 Jack 

第一个“内'join返回朋友圈,第二个'left'join从圆圈加入一级好友 - > f3.user_id为null的位置删除first-订购朋友。 最后的f.user_id <> f2.friend_id是删除一个用户成为他自己的共同朋友。

0

试试这个

SELECT DISTINCT f1.user_id, f1.friend_id 
FROM friend f1 
WHERE (
    user_id = $id 
    OR user_id IN (
     SELECT f2.friend_id 
     FROM friend f2 
     WHERE user_id = $id)) 
    AND (friend_id IN (
     SELECT f3.friend_id 
     FROM friend f3 
     WHERE user_id = $id))