我有一个包含三个表的天气数据库:Locations,WeekDays和Weather,他们有以下列
Locations
location_id | location_name
Weekdays
day_id | day_name
Weather
location_id | day_id | max_temp | min_temp | avg_temp | humidity | rainfall | windspeed
location_id
和day_id
是外键。现在我需要在周日 - 周一的整个星期内返回某个位置的所有天气元素。我确信我应该使用AS 'monday_max_temp'
,AS 'tuesday_rainfall'
等关键字。结果应该是7(天)*我在数据库中为每个位置提供的天气元素的数量。有人可以帮我解决一下我可以用来实现这个问题的SQL查询吗?
答案 0 :(得分:1)
首先:
SELECT
Locations.location_id, Locations.location_name,
Weekdays.day_id, Weekdays.day_name,
Weather.*
FROM Locations
CROSS JOIN Weekdays
LEFT JOIN Weather
ON Weekdays.day_id = Weather.day_id AND Locations.location_id = Weather.location_id
您能否详细解释一下'关键字'。你是什么意思/想要他们?
为什么要排除该位置?你不想要每个地点七天?
我已经看到了你的回复,我会告诉你SQL。你可以在SLQ中做你所要求的,但是没有太多的程序员会选择这种方法。最好在演示文稿中制作交叉表。
SELECT
Locations.location_id, Locations.location_name,
WeatherMonday.max_temp AS monday_max_temp, WeatherMonday.min_temp AS monday_min_temp, ... ,
WeatherTuesday .max_temp AS tues_max_temp, ... ,
... ,
FROM Locations
INNER JOIN Weather AS WeatherMonday ON WeatherMonday.day_id = 1 AND Locations.location_id = WeatherMonday.location_id
INNER JOIN Weather AS WeatherTuesday ON WeatherTuesday.day_id = 2 AND Locations.location_id = WeatherTuesday.location_id
...
答案 1 :(得分:0)
怎么样:
SELECT * FROM Weather WHERE location_id = "desired id" order by day_id desc limit 7;
假设您的day_id是自动增量字段,并且您每天都会添加一行。从最后一次插入到第一次插入所需的位置,您将获得最后7行。