I have a database with three tables:
relation_type table
id relation_title
----------------------
1 father
2 mother
3 son
4 daughter
5 husband
6 wife
users table
id user_name
----------------------
1 amr ali
2 ali saad
3 amal samir
4 sara said
5 said mohammed
6 mona ashraf
relationships table
id first_id second_id relation_type_id
---------------------------------------------------------
1 1 2 3
2 2 1 1
3 1 3 3
4 3 1 2
5 1 4 5
6 4 1 6
7 4 5 4
8 5 4 1
9 5 6 5
10 6 5 6
When I run the query I get the result below:
SELECT u1.user_name,
u2.user_name,
r_t.relation_title
FROM relationships r
JOIN relation_type r_t ON r.relation_type_id = r_t.id
JOIN users u1 ON r.first_id = u1.id
JOIN users u2 ON r.second_id = u2.id
WHERE first_id = 1
================================================
user_name user_name relation_title
------------------------------------------------
amr ali ali saad son
amr ali amal samir son
amr ali sara said husband
What I want to get when I want to draw the chain of relationships between two persons who are not directly related with relationship, like "amr ali" and "mona ashraf" ... How do I get this the following figure via a SQL query
================================================
user_name user_name relation_title
------------------------------------------------
amr ali sara said husband
sara said said mohammed daughter
said mohammed mona ashraf husband