如何根据多个表选择SQL结果

发布于 2024-11-18 14:37:56 字数 260 浏览 3 评论 0原文

我需要根据其他几个表中的某些匹配值从一个表中选择结果。我有下表:

person: id, firstname, lastname
team: id, teamname
player: id, person_id(FK), team_id(FK)
coach: id, person_id(FK), team_id(FK)

我需要返回每支球队的所有教练和球员姓名。我只使用过内部联接,而且似乎我不能在这里使用它们,所以知道如何做到这一点吗?

I need to select results from one table based on certain matching values in a couple of other tables. I have the following tables:

person: id, firstname, lastname
team: id, teamname
player: id, person_id(FK), team_id(FK)
coach: id, person_id(FK), team_id(FK)

I need to return all the coaches and players names for each team. I've only ever used inner joins, and it doesn't seem like I can use those here, so any idea how to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤芳又自赏 2024-11-25 14:37:56

这将为您提供教练:

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

这将为您提供球员:

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

因此,不优雅、简单的答案是将它们与 UNION 一起扔掉。

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.

寒江雪… 2024-11-25 14:37:56

只需在加入团队时使用 OR

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

或者如果您愿意并且您的数据库具有 COALESCE

   LEFT JOIN team t
        ON COALESCE(pl.team_id,c.team_id)  = t.id

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文