自动化mysql表中的数据计算

时间:2017-06-06 05:16:04

标签: php mysql triggers

我有2个表环境和房间:

Environment
+-------+------------+--------------+----------------------+
| Envid | Agregate   | Availability | RoomNo               |
+-------+------------+--------------+----------------------+

Room
+--------+----------+-------------+------------------+
| RoomNo | Humidity | Temperature | Lighting         |
+--------+----------+-------------+------------------+
|  1     |    50    |  40         |  9               |
|  2     |    79    |  25         |  7               |
|  3     |    50    |  40         |  9               |
+--------+----------+-------------+------------------+

基本上,环境是一张空桌子。 我需要的是自动计算:

  1. 从EACH ROW上的Room中获取湿度,温度和光照值
  2. 将它们总结在一起。我能够做到这一点 -
  3. SELECT RoomNo,Humidity,Temperature,Lighting,Humidity + Temperature + Lighting AS Agregate FROM Room;

    我只需要:

    1. 将环绕表中新计算的“Agregate”存储为“Agregate”

    2. 使用表格的相应房间号码填充(通过外键)。

    3. 编辑: 5.房间的可用性(布尔值),当Agregate>时应更新为1。 100。

      这可以直接在mysql中完成吗?还是用PHP?

      注意:Environment中的RoomNo是外键 房间主键

1 个答案:

答案 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;
|