I have two tables:
// 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
I want to select all friends of Jack
(id = 1
). So here is the query:
select * from friend where user_id = 1
/* output
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
*/
Now I also want to select friends of Jack
's friends. How can I do that?
Note, I don't want to select duplicate rows. So I want this output:
/* expected output:
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
| 3 | 2 |
| 3 | 4 |
| 5 | 2 |
*/