我有2个表环境和房间:
Environment
+-------+------------+--------------+----------------------+
| Envid | Agregate | Availability | RoomNo |
+-------+------------+--------------+----------------------+
Room
+--------+----------+-------------+------------------+
| RoomNo | Humidity | Temperature | Lighting |
+--------+----------+-------------+------------------+
| 1 | 50 | 40 | 9 |
| 2 | 79 | 25 | 7 |
| 3 | 50 | 40 | 9 |
+--------+----------+-------------+------------------+
基本上,环境是一张空桌子。 我需要的是自动计算:
SELECT RoomNo,Humidity,Temperature,Lighting,Humidity + Temperature + Lighting AS Agregate FROM Room;
我只需要:
将环绕表中新计算的“Agregate”存储为“Agregate”
使用表格的相应房间号码填充(通过外键)。
编辑: 5.房间的可用性(布尔值),当Agregate>时应更新为1。 100。
这可以直接在mysql中完成吗?还是用PHP?
注意:Environment中的RoomNo是外键 房间主键
答案 0 :(得分:1)
使用以下触发器填充Environment
表。
delimiter |
CREATE TRIGGER `after_update_Room`
AFTER UPDATE ON `Room` FOR EACH ROW
BEGIN
UPDATE Environment
SET Agregate = NEW.Humidity + NEW.Temperature + NEW.Lighting
WHERE RoomNo = NEW.RoomNo;
END;
|
delimiter |
CREATE TRIGGER `after_insert_Room`
AFTER INSERT ON `Room` FOR EACH ROW
BEGIN
INSERT INTO Environment (`Agregate`, `RoomNo`)
SELECT Humidity+Temperature+Lighting AS Agregate, RoomNo
FROM Room
WHERE RoomNo = NEW.RoomNo;
END;
|