嗨,我需要帮助为下列规则设计数据库表:
需要为每个day.It所需的天气存储数据,以存储系统定义的1或2个天气值。
在设计表时需要应用以下参数。
提前谢谢。
发布于 2016-02-28 13:17:11
如果使用的是MySQL 5.7,则可以使用生成的列:
create table wheather (
temp int,
hot int generated always as (if(temp>30,1,0)) virtual,
cold int generated always as (if(temp<20,1,0)) virtual
);
insert into wheather (temp) values (10), (20), (30), (40);
select * from wheather;
给予:
temp hot cold
-------------------
10 0 1
20 0 0
30 0 0
40 1 0
如果使用早期版本的MySQL (如5.5 ),则使用同样的视图。
更新:来自我了解到的不同位置的阈值不同的注释的。有鉴于此,我建议第二个表保存每个位置的阈值,然后加入这两个表:
create table wheather (
location char(20),
temp int
);
insert into wheather (location, temp) values
('Florida', 10), ('Florida', 20), ('Florida', 30), ('Florida', 40),
('Alaska', 10), ('Alaska', 20), ('Alaska', 30), ('Alaska', 40);
create table thresholds (
location char(20),
low int,
high int,
inrange_lower int,
inrange_upper int,
outrange_lower int,
outrange_upper int
);
insert into thresholds values
('Florida', 30, 60, 35, 45, 20, 50),
('Alaska', 10, 30, 15, 25, 5, 40);
select w.location,
w.temp,
if(w.temp < t.low,'yes','no') as cold,
if(w.temp > t.high,'yes','no') as hot,
if(w.temp between t.inrange_lower and t.inrange_upper,'yes','no') as in_range,
if(w.temp < t.outrange_lower or w.temp > t.outrange_upper,'yes','no') as out_of_range
from wheather w left join thresholds t on w.location=t.location;
给予:
+----------+------+------+-----+----------+--------------+
| location | temp | cold | hot | in_range | out_of_range |
+----------+------+------+-----+----------+--------------+
| Florida | 10 | yes | no | no | yes |
| Florida | 20 | yes | no | no | no |
| Florida | 30 | no | no | no | no |
| Florida | 40 | no | no | yes | no |
| Alaska | 10 | no | no | no | no |
| Alaska | 20 | no | no | yes | no |
| Alaska | 30 | no | no | no | no |
| Alaska | 40 | no | yes | no | no |
+----------+------+------+-----+----------+--------------+
8 rows in set (0.00 sec)
代码工作正常,但经过简化,即缺少PKs、索引、FK约束和日期列。我可能搞错了实际值和/或比较,但它可能指向一个方向。
当然,您可以为SELECT语句创建一个视图。如果您真的想存储这些值,那么我建议在WHEATHER表中增加四个列(冷/热/ in _range/out__range),并使用来自阈值表的值填充它们。这样,您以后可以更改阈值(在阈值中),而无需更改WHEATHER中的值。例如,如果您在50年前创建了数据库,那么50°F将被认为是热的,而同时55°F是热的(由于气候变化)。这取决于您的用例。视图提供“生命更新”,触发器提供“历史价值”。
https://stackoverflow.com/questions/35682799
复制相似问题