Unir tres tablas usando MySQL

Resuelto PHP Ferrari asked hace 14 años • 11 respuestas

tengo tres tablas nombradas

**Student Table**
-------------
id    name
-------------
1     ali
2     ahmed
3     john
4     king

**Course Table**
-------------
id    name
-------------
1     physic
2     maths
3     computer
4     chemistry

**Bridge**
-------------
sid    cid
-------------
1     1
1     2
1     3
1     4
2     1
2     2
3     3
3     4
4     1
4     2

Ahora para mostrar el nombre del estudiante con el nombre del curso que había estudiado,

**Result**
---------------------------
Student        Course
---------------------------
ahmed         physic
ahmed         maths
ahmed         computer
ahmed         chemistry
ali           physic
ali           maths
john          computer
john          chemistry
king          physic
king          maths

Construyo la siguiente consulta

select s.name as Student, c.name as Course from student s, course c join bridge b on c.id = b.cid order by s.name

Pero no devuelve el resultado requerido...

¿Y cuál sería la forma normalizada, si quiero saber quién es el administrador y no el otro?

**employee**
-------------------
id        name
-------------------
1         ali
2         king
3         mak
4         sam
5         jon

**manage**
--------------
mid      eid
--------------
1         2
1         3
3         4
4         5

Y quiere obtener este resultado:

**result**
--------------------
Manager      Staff
--------------------
ali          king
ali          mak
mak          sam
sam          jon
PHP Ferrari avatar Sep 14 '10 20:09 PHP Ferrari
Aceptado

Utilice la sintaxis ANSI y quedará mucho más claro cómo une las tablas:

SELECT s.name as Student, c.name as Course 
FROM student s
    INNER JOIN bridge b ON s.id = b.sid
    INNER JOIN course c ON b.cid  = c.id 
ORDER BY s.name 
D'Arcy Rittich avatar Sep 14 '2010 14:09 D'Arcy Rittich

Simplemente use:

select s.name "Student", c.name "Course"
from student s, bridge b, course c
where b.sid = s.sid and b.cid = c.cid 
raisyn avatar Sep 14 '2010 14:09 raisyn

Para normalizar la forma

select e1.name as 'Manager', e2.name as 'Staff'
from employee e1 
left join manage m on m.mid = e1.id
left join employee e2 on m.eid = e2.id
PHP Ferrari avatar Sep 21 '2010 06:09 PHP Ferrari