How to select SQL results based on multiple tables

限于喜欢 提交于 2019-11-28 17:53:47
Chris Cunningham

This will give you the coach:

SELECT team.Teamname, person.Firstname, person.Lastname
FROM person
JOIN coach ON person.id = coach.person_id
JOIN team  ON coach.team_id = team.id

And this will give you the players:

SELECT team.Teamname, person.Firstname, person.Lastname
FROM person
JOIN player ON person.id = player.person_id
JOIN team  ON player.team_id = team.id

So, the non-elegant, simple answer is to just toss it all together with UNION.

Just use an OR in the join to Team

SELECT
     P.firstname,
     P.lastname,
     T.teamname
FROM
    person p id
    LEFT JOIN player pl
    ON p.id = pl.person_id
    LEFT JOIN coach c
    ON p.id = c.person_id
    LEFT JOIN team t
    ON pl.team_id = t.id
         or.c.team_id = t.id

Or if you perfer if and your database has COALESCE

   LEFT JOIN team t
        ON COALESCE(pl.team_id,c.team_id)  = t.id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!