SQL Self Join表-1个表中的所有记录,另一个表中的1条记录

时间:2019-03-19 16:08:26

标签: sql ms-access

我有一个看起来像这样的表(在MS Access中)

rDate      |  rTime  |  Horse  |  Pos  |  Odds
------------------------------------------
01/03/2019 |  13:00  |  HorseA |   3   |  13.2
01/03/2019 |  13:00  |  HorseB |   2   |  3.2
01/03/2019 |  13:00  |  HorseC |   1   |  2.0
01/03/2019 |  13:00  |  HorseD |   4   |  30.0
01/03/2019 |  14:30  |  HorseA |   4   |  6.6
01/03/2019 |  14:30  |  HorseB |   3   |  2.7
01/03/2019 |  14:30  |  HorseC |   2   |  15.0
01/03/2019 |  14:30  |  HorseD |   1   |  8.6
etc...

我想加入表格,并在每场比赛的每匹马旁边显示比赛获胜马的赔率,所以它看起来像这样:

rDate      |  rTime  |  Horse  |  Pos  |  Odds  |  OddsOfWinner
----------------------------------------------------------------
01/03/2019 |  13:00  |  HorseA |   3   |  13.2  |    2.0
01/03/2019 |  13:00  |  HorseB |   2   |  3.2   |    2.0
01/03/2019 |  13:00  |  HorseC |   1   |  2.0   |    2.0
01/03/2019 |  13:00  |  HorseD |   4   |  30.0  |    2.0
01/03/2019 |  14:30  |  HorseA |   4   |  6.6   |    8.6
01/03/2019 |  14:30  |  HorseB |   3   |  2.7   |    8.6
01/03/2019 |  14:30  |  HorseC |   2   |  15.0  |    8.6
01/03/2019 |  14:30  |  HorseD |   1   |  8.6   |    8.6
etc...

到目前为止,我已经尝试了以下查询,但没有一个能按预期运行,我敢肯定其中一个只需要在某个地方进行一些调整即可:

SELECT A.*, B.Odds FROM Results A
INNER JOIN (SELECT ODDS FROM Results B WHERE A.rDate = B.rDate AND Pos = 1) 
AS temp
ON A.rDate = B.rDate AND A.rTime = B.rTime
WHERE A.rDate >= #2018/01/01#;

----------------------------------------------------------------------

SELECT A.*, B.Odds
FROM Results A, Results B
WHERE A.rDate = B.rDate AND A.rTime = B.rTime
AND A.rDate >= #2018/01/01#;

2 个答案:

答案 0 :(得分:1)

您可以为此使用相关子查询:

select r.*,
       (select r2.odds
        from results as r2
        where r2.rdate = r.rdate and r2.rtime = r.time and
              r2.pos = 1
       ) as winning_odds
from results as r;

为了提高性能,只需添加索引results(rdate, rtime, pos, odds)

答案 1 :(得分:1)

您还可以通过以下方式使用inner join

select 
    r1.*, q.wodds
from 
    results r1 inner join
    (select r2.rdate, r2.rtime, r2.odds as wodds from results r2 where r2.pos = 1) q 
    on r1.rdate = q.rdate and r1.rtime = q.rtime
where 
    r1.rdate >= #2018/01/01#

联接通常比相关子查询更有效,因为必须为数据集中的每个记录评估子查询。