内部加入两个表并仅显示最新记录(mySQL)

时间:2016-02-05 02:16:15

标签: mysql sql

我有两个父表在子表中创建一个复合(compresults)

我想获得每位运动员的最新记录(仅1)

我知道答案是选择具有最大日期的比赛并且只显示那种方式,但是我一直试图这样做,但是我无法正确地进行格式化

父表(运动员) +---------+-------+ | athlete | name | +---------+-------+ | 1 | James | | 2 | Gemma | +---------+-------+

家长桌(比赛) +-----+----------+----------+ | cid | compname | compdate | +-----+----------+----------+ | 1 | Comp A | 2015 | | 2 | Comp B | 2014 | +-----+----------+----------+

儿童表(compirsults) +---------+-----+--------+ | athlete | cid | result | +---------+-----+--------+ | 1 | 1 | 500 | | 1 | 2 | 550 | | 2 | 2 | 450 | +---------+-----+--------+

预期结果: +-------+----------+--------+ | name | compname | result | +-------+----------+--------+ | James | Comp A | 500 | | Gemma | Comp B | 450 | +-------+----------+--------+

任何想法?谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用

select b.name,c.compname,a.result from compresults a left join athletes 
b on (a.athlete)=b.athlete
left join competitions c on (a.cid)=c.cid

答案 1 :(得分:0)

我相信这会收到您所追求的结果。

SELECT a.`name`, b.`compname`, c.`result`
FROM `compresults` c
INNER JOIN `competitions` b ON b.cid = c.cid
INNER JOIN `athletes` a ON c.`athlete` = a.`athlete`
WHERE b.`compdate` = (
                                    SELECT co.`compdate` 
                                    FROM `competitions` co INNER JOIN `compresults` cr ON cr.`cid` = co.`cid` 
                                    WHERE cr.`athlete` = a.`athlete`
                                    ORDER BY co.`compdate` DESC LIMIT 1
                    )