【问题标题】:How to join two tables which one has two samples of the other one (and we want to see them all in the final table)如何连接两张表,其中一张有另一张的两个样本(我们希望在决赛桌中看到它们)
【发布时间】:2022-01-05 17:53:33
【问题描述】:

我的 SQL 数据库中有两个表,TeamMatch。每场比赛都有两个团队 ID - 一个用于host_team,一个用于guest_team

我的问题是:我怎样才能加入这两个表来获得匹配的数据,将host_teamguest_team 的完整数据放在一个唯一的数据集中?

团队:

id name
1 x
2 y

匹配:

id host_id guest_id
1 1 2

最终数据集:

match_id host_id host_name guest_id guest_name
1 1 x 2 y

【问题讨论】:

  • 您可以join 表格或使用correlated subquery

标签: sql join


【解决方案1】:

刚刚离开加入团队比赛两次

SELECT 
  match.match_id
, match.host_id
, host.name AS host_name
, match.guest_id
, guest.name AS guest_name
FROM Match AS match
LEFT JOIN Team AS host ON host.id = match.host_id
LEFT JOIN Team AS guest ON guest.id = match.guest_id

【讨论】:

  • 谢谢,这个解决方案有效:)
【解决方案2】:

无论哪种方式,您都需要查询Team 表两次,一种方式是使用与适当的id 相关的内联选择

select m.Id as match_id,
    m.host_id,
    (select name from Team t where t.id=m.host_id) host_name,
    m.guest_id
    (select name from Team t where t.id=m.guest_id) guest_name,
from Match m

【讨论】:

  • 谢谢。我认为这个解决方案也有效!但我需要加入这些表格以达到我的目标
猜你喜欢
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多