我正在创建一个简单的数据库,这将允许我跟踪斯诺克结果,在玩家之间产生头对头的结果。目前我有3个表:(玩家,夹具,结果)
PlayerID PlayerName
1 Michael Abraham
2 Ben Mullen
3 Mark Crozier
FixtureID Date TableNo Group
1 07/12/2015 19:00:00 12 0
2 08/12/2015 12:00:00 9 0
ResultID FixtureID PlayerID FramesWon
1 1 1 3
2 1 3 1
3 2 1 5
4 2 2 1
我想要一个查询,它返回结果表中发生在1号和3号玩家之间的灯具的所有行。目前我的查询是:
SELECT *
FROM Result
WHERE PlayerID IN (1,3);
这将返回结果表的前3行 - 当我只查找前2行时,因为它们共享相同的FixtureID。是否有一种简单的方法可以从此查询结果中删除第三行,还是应该重新考虑我的数据库设计?任何帮助将不胜感激。
答案 0 :(得分:1)
一种解决方案是使用GROUP BY查询,按FixtureID分组并计算每个FixtureID的行数。此查询将选择包含玩家1和3的所有FixtureID:
select
FixtureID
from
Results
where
PlayerID IN (1,3)
group by
FixtureID
having
count(*)=2
然后从结果表中获取记录,您可以使用此查询:
select *
from Results
where FixtureID IN (
select FixtureID
from Results
where PlayerID IN (1,3)
group by FixtureID
having count(*)=2
)
答案 1 :(得分:0)
您可以加入您的灯具表两次,如下所示:
select
*
from
Result as R1
join Result as R2 on R1.FixtureID = R2.FixtureID
where
R1.PlayerID in (1,3)
AND R2.PlayerID in (1,3)
AND R1.PlayerID != R2.PlayerID
group by
R1.FixtureID
;
或者,因为它现在有点乱,所以显示它像斯诺克分数显示经常显示:
select
R1.FixtureID, R1.PlayerID as player1, R1.FramesWon as player1_frames, R1.FramesWon+R2.FramesWon as total_frames, R2.FramesWon as player2_frames, R2.PlayerID as player2
from
Result as R1
join Result as R2 on R1.FixtureID = R2.FixtureID
where
R1.PlayerID in (1,3)
AND R2.PlayerID in (1,3)
AND R1.PlayerID != R2.PlayerID
group by
R1.FixtureID
;