假设下表定义(没有适当的索引或约束)
CREATE TABLE seasons (
id int auto_increment,
competition_id int,
start_date DATE,
end_date DATE,
description varchar(32),
primary key(id)
)
CREATE TABLE rounds (
id int auto_increment,
season_id int,
start_date DATE,
end_date DATE,
description varchar(32),
primary key(id)
)
和一些示例数据
INSERT INTO seasons (competition_id,start_date,end_date,description) VALUES
(1, '2007-3-15', '2007-9-15', 'FooCup 2007'),
(1, '2008-3-7', '2007-9-21', 'FooCup 2008'),
(1, '2009-4-1', '2007-9-21', 'FooCup 2009'),
(2, '2009-1-1', '2009-12-20', 'xyz 2009')
INSERT INTO rounds (season_id, start_date, end_date, description) VALUES
(1, '2007-3-15', '2007-4-15', 'foo 2007 1'),
(1, '2007-4-16', '2007-8-15', 'foo 2007 2'),
(1, '2007-8-16', '2007-9-15', 'foo 2007 3'),
(2, '2008-3-7', '2008-4-21', 'foo 2008 1'),
(2, '2008-4-21', '2008-8-16', 'foo 2008 2'),
(2, '2008-8-17', '2008-9-21', 'foo 2008 3'),
(3, '2009-4-1', '2009-5-1', 'foo 2009 1'),
(3, '2009-5-2', '2009-8-1', 'foo 2009 2'),
(3, '2009-8-2', '2009-9-21', 'foo 2009 3'),
(4, '2009-1-1', '2009-12-20', 'xyz ')
您修复时间/日期(FD),并希望有此记录fd在start_date和end_date之间。 BETWEEN ... AND ...测试完全相同,并与日期/时间值一起使用。 例如
SELECT
id, description
FROM
round as r
WHERE
'2008-6-17' BETWEEN r.start_date AND r.end_date
当时返回所有回合(所有比赛)的记录。
现在你加入季节表的season_id。并将结果限制在某个competition_id(如果您想要的话)。
SELECT
r.description as rd, r.start_date, r.end_date
FROM
rounds as r
JOIN
seasons as s
ON
r.season_id=s.id
WHERE
'2009-6-17' BETWEEN r.start_date AND r.end_date
AND s.competition_id=1
编辑:对不起,误解了问题.... 假设你知道competition_id并有固定日期(2009-08-16),你可以得到的季节。编号与
SELECT
s.id
FROM
seasons as s
WHERE
s.competition_id=1
AND '2009-08-16' BETWEEN s.start_date AND s.end_date
现在您可以加入season.id = rounds.season_id以获得本赛季的所有回合。
SELECT
r.id
FROM
seasons as s
JOIN
rounds as r
ON
s.id=r.season_id
WHERE
s.competition_id=1
AND '2009-08-16' BETWEEN s.start_date AND s.end_date
(rounds:id 7,8,9 in this case)。
将结果限制为最高的round.id最简单的选项是让MySQL按照顺序四舍五入来按顺序四舍五入,并将结果限制为一条记录。
SELECT
r.id
FROM
seasons as s
JOIN
rounds as r
ON
s.id=r.season_id
WHERE
s.competition_id=1
AND '2009-08-16' BETWEEN s.start_date AND s.end_date
ORDER BY
r.id DESC
LIMIT
1
使用EXPLAIN SELECT ...以确保查询不太效率低下......
我不明白这一点 - 有很多谈论日期和轮,但例如加入到'season_id'?你有什么,你想要什么最终产出? – 2009-12-10 06:44:55
赛季是数据库中的一个条目,每赛季更新一次,因为有些比赛会更改他们对本赛季赞助商的名称。至少每轮至少会有一次轮换,但可能会有更多的变化。在某些比赛中,如欧足联,他们有一些第一轮淘汰赛,然后是小组阶段,然后再次淘汰,这将导致3轮不同。最终产出应该是每个季节目前活跃的每一轮的清单。 – yoda 2009-12-10 06:54:48
很高兴知道,但我仍然一无所知,对不起。 – 2009-12-10 07:01:25