Let's say I have 3 DB tables:
- teachers, with the following fields:
- id
- name
- subjects, with the following fields:
- id
- name
- teachers-subjects, with the following fields:
- teacher_id
- subject_id
So, a relationship comes some teachers have subjects in common.
I've thought about the algorithm for querying:
For each record s in subjects table:
Select the count in teachers_subjects table.
If count is greater than 1
In teacher_subjects, get teacher_id's where subject_id is s.Make the relationship pairs.
I'd like to get as output something like:
+----------+----------+---------------+
| Teacher1 | Teacher2 | Relationships |
+----------+----------+---------------+
| John | Larry | 10 |
| John | Samantha | 12 |
| Samantha | Larry | 9 |
| Ian | Louis | 3 |
+----------+----------+---------------+
And if I needed to retrieve which subjects made a relationship, we'd need to get something like:
+----+----------+----------+
| id | teacher1 | teacher2 |
+----+----------+----------+
| 1 | John | Larry |
| 2 | John | Samantha |
| 3 | Samantha | Larry |
| 4 | Ian | Louis |
+----+----------+----------+
And something like:
+-----+------------+
| id | subject |
+-----+------------+
| 1 | math |
| 1 | english |
| 1 | science |
| ... | ... |
| ... | ... |
| 4 | science |
| 4 | literature |
| 4 | databases |
+-----+------------+
Graphically, I'm representing this in a graph consulted over a web browser:
So when I hover one edge, it displays the relationships information.
I'll receive queries result over php programming, What such queries or stored procedure would produce me such required outputs?