从事件中选择各种值

时间:2016-06-14 19:11:05

标签: mysql sql database database-design mysql-workbench

我有下面这3张桌子,我想列出所有赢得金牌的运动员

Athletes
    +------------+-----------------+
    | athletesID | athletesName    |
    +------------+-----------------+
    | jg         | justin gatlin   |
    | ms         | maria sharapova |
    | ub         | usain bolt      |
    | vw         | venus williams  |
    +------------+-----------------+

events
    +---------+-----------+---------------------+
    | eventID | eventName | athletes_athletesID |
    +---------+-----------+---------------------+
    | ev1     | tennis    | ms                  |
    | ev1     | tennis    | vw                  |
    | ev2     | mens 100m | jg                  |
    | ev2     | mens 100m | ub                  |
    +---------+-----------+---------------------+
results

    +-----------+--------+----------------+----------------------------+
    | resultsID | Medal  | events_eventID | events_athletes_athletesID |
    +-----------+--------+----------------+----------------------------+
    | results1  | silver | ev1            | ms                         |
    | results1  | Gold   | ev1            | vw                         |
    | results2  | silver | ev2            | jg                         |
    | results2  | Gold   | ev2            | ub                         |
    +-----------+--------+----------------+----------------------------+

到目前为止,我已经使用了下面这段代码,但是这列出了所有获得金牌的银牌得主

SELECT 
    athletesID, athletesName, medal
FROM
    myoly.athletes
        JOIN
    myoly.events ON athletes.athletesID = events.athletes_athletesID
        JOIN
    myoly.results ON myoly.events.eventID = myoly.results.events_eventID
WHERE
    medal = 'gold';

如何列出所有仅获得金牌的运动员?

2 个答案:

答案 0 :(得分:1)

SELECT 
    a.athletesID, 
    a.athletesName, 
    r.medal
FROM results r
LEFT JOIN athletes a
ON a.athletesID  = r.events_athletes_athletesID 
WHERE r.medal = 'Gold';

答案 1 :(得分:1)

如果您删除WHERE medal = 'gold'并查看结果,则应该会为您提供有关问题的线索。这通常是排除故障的最佳方法。

无论如何,您需要在results而不是athletes加入athleteIDeventID。这是因为你关注哪些运动员赢得金牌而不是哪些赛事有金牌

SELECT     a.athletesID, 
           a.athletesName, 
           r.medal
FROM       athletes a
INNER JOIN results r ON a.athletesID  = r.events_athletes_athletesID 
WHERE      r.medal = 'Gold'