我有两个表,一个国家表和一个天气表。我想检索过去 15 天内没有下雨的所有国家/地区的名称。
天气表有一列叫做“DayNum”,从 1 -> 无穷大,每天增加 1,它是唯一的。该表还有一个名为“Rain”的列,它只是一个 0 或 1 的 bool 值。
此外,并非所有国家/地区都在同一天添加,因此每个国家/地区的最大 DayNum 会有所不同。
下表示例(为了便于阅读,数据被删减):
国家:
ID Name
1 USA
2 Cananda
3 Brazil
天气
ID Country_id DayNum Rain
1 1 1 0
2 1 2 0
3 1 3 1
这是我目前的查询尝试(已经为此工作了好几天):
SELECT countries.name, weather.daynum
FROM countries INNER JOIN weather ON countries.id = weather.country_id
GROUP BY countries.name
HAVING weather.daynum > (MAX(weather.day_num) - 15) AND SUM(weather.rain) = 0;
我认为这应该可行,但我遇到了严重的性能问题。我需要编写的实际查询处理不同的数据(相同的确切概念)和数百万行。此查询似乎以指数速度变慢。
有人可以提供任何建议吗?
我的另一个想法是以某种方式将 JOIN 限制为仅获取前 15 条记录(同时按 weather.day_num 进行排序),但我还没有找到在 JOIN 中执行此操作的方法(如果可能的话)。
最佳答案
你对雨量不感兴趣,只关心它是否存在,所以...
select * from countries
left join
(
select weather.country_id
from weather
inner join
(select country_id, MAX(daynum) as maxdaynum from weather group by country_id) maxday
on weather.country_id = maxday.country_id
and weather.daynum>maxday.maxdaynum-3
where rain=1
) rainy
on countries.id = rainy.country_id
where country_id is null
我假设您已经适本地为表编制了索引
关于mysql - SQL 查询 - 仅当值在 "last n records"范围内时获取行(特定于记录),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11723262/