2

Here are my tables: School Class Kid.

Each class belongs to one school.

Each kid belongs to one class.

All tables have an auto incrementing primary key.

Class has a foreign key pointing to the school's primary key that it belongs to. Same with Kid pointing to the primary key of the Class they belong to.

If I wanted to select kid.id, kid.name, school.id, school.name how would I do this in one query?

This result would return a record for each kid with their id and name. It would also include their school id and name.

SCHOOL
------     
id-primary     
eyname

CLASS
-----
id-primary key         
school_id-foreign key to school name

KID
---
id-primary key           
class_id-foreign key to class name
4

4 に答える 4

1

を使用するだけですJOIN。次のようにします。

SELECT kid.id, kid.name, school.id, school.keyname
FROM kid
JOIN class on class.id = kid.class_id
JOIN school on school.id = class.school_id

また、次のようにすることもできます。

SELECT kid.id, kid.name, school.id, school.name
FROM kid, class, school
WHERE class.id = kid.class_id and school.id = class.school_id
于 2013-01-30T22:46:15.203 に答える
0
Select kid.id,kid.Name,school.Id,school.keyname
From kid
Inner join Class On k.Class_id = Class.Id
Inner join School On Class.school_id = school.id
于 2013-01-30T22:49:21.727 に答える
0

あなたが探しているのは、すべての子供のエンティティが最終的に学校にマッピングされる場合の INNER JOIN です。別の JOIN が必要になる場合があります。それ以外の場合は、LEFT または RIGHT 結合です。

SELECT kids.id、kids.name、schools.id、schools.name FROM kids INNER JOIN classes ON kids.class_id = classes.id INNER JOINschools ONschools.id = classes.school_id;

于 2013-01-30T22:57:04.033 に答える
0
select s.*, c.*, k.* 
from school s 
left join class c on c.school_id=s.id
left join kid k on k.class_id=c.id
于 2013-01-30T23:03:01.927 に答える