如何为这种情况编写sql

时间:2013-07-02 23:34:02

标签: mysql sql

我对如何为这个场景制作sql语句感到很困惑。我一直在尝试,但没有运气,所以希望有人可以提供帮助。我有3个表:表父母,表儿童和表学校

-PARENTS has
ID      name


-Children has
ID    parentID   nam

-SCHOOL has 

ID   parentID   chidrenID   schoolType

我想要的是让所有父母带着孩子(无论他们是否在学校注册),但如果他们在学校注册,那么我需要将schoolType变为“highschool”

所以沿着这些方向(pseaduo代码):

Select * from parents,children 
where parents.ID = Children.parentID and 
include school information 
where parents.ID = school.parentID and 
children.ID = school.childrenID and schoolType = "HighSchool"

任何帮助???

2 个答案:

答案 0 :(得分:0)

SELECT
  *
FROM PARENTS p
INNER JOIN CHILDREN c ON p.ID = c.parentID
LEFT JOIN SCHOOL s ON c.ID = s.childrenID AND 'HighSchool' = s.schoolType

答案 1 :(得分:0)

我认为你需要这样的东西:

SELECT * from PARENTS P
         inner join CHILDREN C
             on P.ID=C.parentID
         left join SCHOOL S
            on  P.ID=S.parentID
            and C.ID=S.childrenID
WHERE S.schoolType is null
   OR S.schoolType = 'HighSchool'