dpqmu84646 2013-12-03 20:39
浏览 21

Multiples SQL连接

I have this problem and I haven't been able to figure out how can I make this work.

I have a table called "parents" and a table called "students"

Parents table has

id, name, lastname and type. "Type" cantains something like "mother" or "father".

Students table has

id, name, lastname, motherid(parents table), fatherid(parents table).

How can I make a query with JOINS that returns the Mother's name and the Father's name? And knowing that the parents can have multiple children, and obviously a student can have two parents, Mother and Father...

I hope I explained it well, thank you beforehand

  • 写回答

2条回答 默认 最新

  • douchen1988 2013-12-03 20:45
    关注

    This is the simple way to do what you're asking:

    (
        SELECT      KIDS1.id as student_id
                    KIDS1.name as student_firstname
                    KIDS1.lastname as student_lastname
                    MOMS.id as parent_id
                    MOMS.name as parent_firstname
                    MOMS.lastname as parent_lastname
                    MOMS.type as parent_type
        FROM        students KIDS1
        JOIN        parents MOMS ON KIDS1.motherid = MOMS.id
    )
    UNION
    (
        SELECT      KIDS2.id as student_id
                    KIDS2.name as student_firstname
                    KIDS2.lastname as student_lastname
                    DADS.id as parent_id
                    DADS.name as parent_firstname
                    DADS.lastname as parent_lastname
                    DADS.type as parent_type
        FROM        students KIDS2
        JOIN        parents DADS ON KIDS2.fatherid = DADS.id
    )
    

    I've updated my query now so that you can get a list of the parents and what kind of parent it is (mother or father). This query will not list students that don't have a parent listed in your system. You will have to modify or write a different query to determine which students do not have a parent listed.

    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程