Oracle:将具有“多”表的连接限制为仅一个实例?

时间:2014-04-15 13:54:35

标签: oracle join

此查询返回包含赛马结果的宽表。然而,一匹马有多个训练师,因此这个联赛为马匹的每个训练师返回相同的比赛结果。我该如何解决这个问题?我一直在玩Group By,但甲骨文似乎并不喜欢它。

SELECT 
    b.meet_name AS Course, 
    a.race_time AS Time, 
    (f.jf_name||' '||f.jl_name) AS Jockey,     
    e.horse_name AS Horse, 
    c.odds, 
    d.place, 
    d.race_comment AS Note, 
    (g.bf_name||' '||g.bl_name) AS Breeder, 
    (h.tf_name||' '||h.tl_name) AS Trainer, 
    a.race_type AS Type, 
    a.distance AS     Furlongs, 
    a.prize_money AS "Prize Money", 
    a.ground AS Ground
    FROM proj_race_details a
    JOIN proj_meet b ON a.meet_id = b.meet_id
    JOIN proj_entry c ON c.race_id = a.race_id
    JOIN proj_results d ON d.race_id = c.race_id AND d.horse_id = c.horse_id
    JOIN proj_horses e ON e.horse_id = d.horse_id
    JOIN proj_jockey f ON f.jockey_id = d.jockey_id
    JOIN proj_breeder g ON g.breeder_id = e.breeder_id
    JOIN proj_trainer h ON h.trainer_id = e.trainer_id;

1 个答案:

答案 0 :(得分:1)

修改

此查询每匹马只会选择一名教练。培训师的名字将是第一个,按字母顺序排序。

SELECT 
    b.meet_name AS Course, 
    a.race_time AS Time, 
    (f.jf_name||' '||f.jl_name) AS Jockey,     
    e.horse_name AS Horse, 
    c.odds, 
    d.place, 
    d.race_comment AS Note, 
    (g.bf_name||' '||g.bl_name) AS Breeder, 
    h.Trainer, 
    a.race_type AS Type, 
    a.distance AS     Furlongs, 
    a.prize_money AS "Prize Money", 
    a.ground AS Ground
FROM proj_race_details a
JOIN proj_meet b ON a.meet_id = b.meet_id
JOIN proj_entry c ON c.race_id = a.race_id
JOIN proj_results d ON d.race_id = c.race_id AND d.horse_id = c.horse_id
JOIN proj_horses e ON e.horse_id = d.horse_id
JOIN proj_jockey f ON f.jockey_id = d.jockey_id
JOIN proj_breeder g ON g.breeder_id = e.breeder_id
JOIN 
(SELECT ph.horse_id AS horse_id, MIN(pj.tf_name||' '||pj.tl_name) AS Trainer
FROM proj_trainer pj INNER JOIN proj_horses ph
ON pj.trainer_id = ph.trainer_id
GROUP BY ph.horse_id
) h
ON h.horse_id = e.horse_id;