以下是我的表:School
Class
Kid
。
每个班级属于一所学校。
每个孩子属于一个班级。
所有表都有一个自动递增的主键。
Class
有一个外键,指向学校所属的学校主键。与指向其所属Kid
主键的Class
相同。
如果我想select kid.id, kid.name, school.id, school.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
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
如果所有的孩子实体最终都会映射到学校,那么您正在寻找的是内部联接。可能需要不同的JOIN,否则可以是LEFT或RIGHT join。
SELECT kids.id,kids.name,schools.id,schools.name FROM kids INNER JOIN classes ON kids.class_id = classes.id INNER JOIN SCHOOL on schools.id = classes.school_id;
答案 3 :(得分: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