2

这是我的表:School Class Kid

每个班级属于一所学校。

每个孩子属于一个班级。

所有表都有一个自动递增的主键。

Class有一个外键指向它所属的学校的主键。与Kid指向Class它们所属的主键相同。

如果我想select kid.id, kid.name, school.id, school.name如何在一个查询中执行此操作?

此结果将返回每个孩子的记录及其 id 和 name。它还将包括他们的学校 ID 和姓名。

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

如果所有孩子实体最终都将映射到学校,那么您正在寻找的是 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 JOIN school ONschools.id = classes.school_id;

于 2013-01-30T22:57:04.033 回答
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
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 回答