如何加入两个 tables,其中一个有另一个的两个样本(我们希望在最后的 table 中看到它们)
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)
我的 SQL 数据库中有两个表,Team
和 Match
。每场比赛都有两个团队 ID - 一个用于 host_team
,一个用于 guest_team
。
我的问题是:我怎样才能加入这两个表以获得比赛的数据,在一个唯一的数据集中包含 host_team
和 guest_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
刚刚离开加入团队比赛两次
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
无论哪种方式,您都需要查询 Team
table 两次,一种方法是使用在适当的 id
[=13= 上关联的内联-select ]
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
我的 SQL 数据库中有两个表,Team
和 Match
。每场比赛都有两个团队 ID - 一个用于 host_team
,一个用于 guest_team
。
我的问题是:我怎样才能加入这两个表以获得比赛的数据,在一个唯一的数据集中包含 host_team
和 guest_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 |
刚刚离开加入团队比赛两次
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
无论哪种方式,您都需要查询 Team
table 两次,一种方法是使用在适当的 id
[=13= 上关联的内联-select ]
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