I have a table like this:
id (PK)   name    teacher (FK)    student (FK)
   1      Ron         3               6
Both teacher and student are in another table called people.
 people
 id (PK)   name   age
    3      Ali    42
    6      Jon    12
I would like to perform a query to obtain the following
name    teacher's name   student's name
 Ron         Ali              Jon
Is this possible? I know I can perform two separate joins, but then I am left with two rows and there is no indication of which name is the teacher and which is the student
Here is how you would do that: ALTER TABLE my_table ADD FOREIGN KEY (key) REFERENCES other_table(id) ON DELETE SET NULL; And that's it!! That's how you change a foreign key constraint in MySQL!
Of course you can add a foreign key when there is data... assuming you don't have any values that violate the new constraint.
Dropping Foreign Key Constraints You can drop a foreign key constraint using the following ALTER TABLE syntax: ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol; If the FOREIGN KEY clause defined a CONSTRAINT name when you created the constraint, you can refer to that name to drop the foreign key constraint.
select t.name, p1.name teacher_name, p2.name student_name 
       from t
left join people p1 on (t.teacher=p1.id)
left join people p2 on (t.student=p2.id)
                        Try this:
SELECT a.name, b.name 'teacher name', c.name 'student name'
FROM mainTablle a 
LEFT JOIN people b ON a.teacher = b.id 
LEFT JOIN people c ON a.student = c.id 
WHERE a.id = 1;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With