我有三个表如下:
IDS:
id | id_code
1 | abcde
2 | jklmn
3 | pqrst
播放器:
full_name| initials
john s. | js
anne p. | ap
jen l. | jl
游戏:
id | player | points | player2 | points2
1 | js | 2 | ap | 1
2 | ap | 1 | jl | 3
2 | jl | 3 | js | 4
3 | jl | 4 | ap | 1
==
我想获得以下输出:
id | id_code | full_name | points | full_name_player_2 | points2
我无法弄清楚如何使用多个连接语句来执行此操作...
答案 0 :(得分:0)
这是连接表的示例,其中内部表的连接将加入游戏。
select p1.*, i1.*, g.*, p2.*, i2.* from
games g inner join (player p1 inner join id i1 on p1.id = i1.id)
on g.player = p1.initials
inner join (player p2 inner join id i2 on p2.id = i2.id)
on g.player2 = p2.initials
答案 1 :(得分:0)
<强>更新强>
使用新结构:
select i.id, i.id_code, p1.full_name, g.points, p2.full_name, g.points2
from
@ids as i
inner join @games as g on g.id = i.id
inner join @players as p1 on g.player = p1.initials
inner join @players as p2 on g.player2 = p2.initials
OLD DATABASE
我认为这会得到你的结果。如果有效,请告诉我。
select i.id, i.id_code, p1.full_name, g.points, p2.full_name, g.points2
from
@ids as i
inner join @players as p1 on p1.id = i.id
inner join @games as g on g.player = p1.initials
inner join @players as p2 on g.player2 = p2.initials
测试用例
declare @ids table (
id int,
id_code nvarchar(200)
)
declare @players table (
id int,
full_name nvarchar(200),
initials nvarchar(200)
)
declare @games table (
player nvarchar(200),
points int,
player2 nvarchar(200),
points2 int
)
insert into @ids (id, id_code) values (1, 'abcde')
insert into @ids (id, id_code) values (2, 'jklmn')
insert into @ids (id, id_code) values (3, 'pqrst')
insert into @players (id, full_name, initials) values (1, 'john s.', 'js')
insert into @players (id, full_name, initials) values (2, 'anne p.', 'ap')
insert into @players (id, full_name, initials) values (3, 'jen l.', 'jl')
insert into @games (player, points, player2, points2) values ('js', 2, 'ap', 1)
insert into @games (player, points, player2, points2) values ('ap', 1, 'jl', 3)
insert into @games (player, points, player2, points2) values ('jl', 3, 'js', 4)
insert into @games (player, points, player2, points2) values ('jl', 4, 'ap', 1)