我有2个mysql表,如下例所示:
CARS:
RaceID CarID Dis Grd Date Time
8 1 200 A 2010-10-10 20.50
8 2 300 A 2010-10-10 30.50
8 3 200 A 2010-10-10 20.10
9 1 200 A 2010-11-10 20.00
12 1 200 A 2011-12-11 19.50
RACES:
RaceId CarID Dis Grd Date Exp_Time
10 1 200 A 2011-11-11
10 2 200 A 2011-11-11
10 3 200 A 2011-11-11
我想根据来自CARS表的数据在Exp_Time列添加Races表上的数据。 例如:
RACES.Exp_Time=AVG(CARS.Time)
WHERE
CARS.CarID=RACES.CarID
CARS.Dis=RACES.Dis
CARS.Grd=RACES.Grd
CARS.Date<RACES.Date
这个想法是预期的时间是相同距离和grd之前的比赛时间的AVG。未来的比赛应该从计算AVG中排除 问题是从RACES表中获取日期条件。 我这样查询:
UPDATE `RACES` c
INNER JOIN (
SELECT CARS.CarID, CARS.Dis, CARS.Grd, CARS.Date, AVG(Time) AS `Exp_Time`
FROM CARS
WHERE CARS.Date<'2011-11-11'
GROUP BY CarID, Dis, Grd
)
x ON c.CarID=x.CarID AND c.Dis=x.Dis AND c.Grd=x.Grd
SET c.Exp_Time=x.Exp_Time
当我输入myseld日期时 - 2011-11-11 我不知道如何从RACES表中获取数据。
有人可以帮忙吗? 提前致谢! 伊万
答案 0 :(得分:2)
2011-11-11我不知道如何从RACES表中获取数据。
您可以将此谓词移动到JOIN
条件,如下所示:
UPDATE `RACES` c
INNER JOIN (
SELECT
CarID, Dis, Grd, Date, AVG(Time) AS `Exp_Time`
FROM CARS
GROUP BY CarID, Dis, Grd
)x ON c.CarID = x.CarID
AND c.Dis = x.Dis
AND c.Grd = x.Grd
AND x.DATE(`Date`) < c.DATE(`Date`)
SET c.Exp_Time = x.Exp_Time;
答案 1 :(得分:2)
UPDATE `RACES` c
INNER JOIN (
SELECT CARS.CarID, CARS.Dis, CARS.Grd, CARS.Date, AVG(Time) AS `Exp_Time`
FROM CARS
WHERE CARS.Date < (SELECT Date
FROM RACES
WHERE CARS.Date<RACES.Date
AND CARS.Grd=RACES.Grd
AND CARS.CarID=RACES.CarID
AND CARS.Dis=RACES.Dis
LIMIT 1
)
GROUP BY CarID, Dis, Grd
)
x ON c.CarID=x.CarID AND c.Dis=x.Dis AND c.Grd=x.Grd
SET c.Exp_Time=x.Exp_Time