Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL replace foreign key in result table with data from FK table

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

like image 806
Roger Jarvis Avatar asked Dec 19 '12 08:12

Roger Jarvis


People also ask

Can we update foreign key in a table MySQL?

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!

Can I add a foreign key constraint to an existing table with data?

Of course you can add a foreign key when there is data... assuming you don't have any values that violate the new constraint.

How do I remove a foreign key from a table in MySQL?

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.


2 Answers

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)
like image 57
valex Avatar answered Oct 20 '22 19:10

valex


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;
like image 8
Saharsh Shah Avatar answered Oct 20 '22 17:10

Saharsh Shah