【发布时间】:2017-07-02 09:04:30
【问题描述】:
这是我的表结构:
// 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 层中做到这一点?
视觉示例及其预期输出:
【问题讨论】:
-
在第二个
select ..添加一个选择计数条件,应该可以完成这项工作。 -
更新您的问题并添加您选择的实际结果和预期结果..(基于您的数据样本)
-
@scaisEdge 预期输出已添加。
-
我不明白您的预期输出。您正在寻找朋友的朋友,对吗?那么为什么会有 1 - 3 和 1 - 4 呢?