MySQL查询通过查看历史日志来查找当前状态

时间:2014-10-22 12:27:13

标签: mysql

数据库表:

服务(身份证,姓名)

历史(id,service_id,status,message,smessage,date),其中status为0到4之间的整数。

我试图根据该服务的历史记录找出每个不同service_id的当前状态。 当计划维护时,它将在未来的开始和结束时间输入数据库,直到现在我用它来计算状态:

SELECT
    d. NAME,
    d.id,
    c.date,
    COALESCE (c.smessage, 'Normal') AS smessage,
    COALESCE (c. STATUS, 0) AS STATUS
FROM
    services d
LEFT JOIN (
    SELECT
        *
    FROM
        history
    WHERE
        id IN (
            SELECT
                max(id)
            FROM
                history
            WHERE
                date < now()
            GROUP BY
                service_id
        )
) c ON d.id = c.service_id;

但是,如果维护重叠,或者提前两周安排维护,而另一次维护计划在接下来的15分钟,则第二次维护无法正确显示。

示例数据

# id  service_id date status message added_by smessage
126 19  2014-10-21 11:32:34 0   Regular Status update.  usr1    Regular update.
125 19  2014-10-23 22:00:00 0   Maint1 done.    usr1    Maint1Done.
124 19  2014-10-23 17:00:00 3   Maint2 done.    usr1    Maint2 done.
123 19  2014-10-21 22:00:00 0   Maint3 done.    usr1    Maint3 done
122 19  2014-10-21 17:00:00 3   Maint3 Sched.   usr1    Maint3 sched
121 19  2014-10-20 22:00:00 0   Maint2 sched.   usr1    maint2 sched 
120 19  2014-10-20 17:00:00 3   Maint1 sched.   usr1    Maint1 sched

1 个答案:

答案 0 :(得分:1)

您拥有正确的基本结构,只需使用date代替id

SELECT s.NAME, s.id, s.date,
       COALESCE(h.smessage, 'Normal') AS smessage,
       COALESCE(h.STATUS, 0) AS STATUS
FROM services s LEFT JOIN
     (SELECT h.*
      FROM history
      WHERE NOT EXISTS (SELECT 1
                        FROM history h2
                        WHERE h2.service_id = h.service_id and
                              h2.date < now() and
                              h2.date > h.date
                      )
      ) h
      ON s.id = h.service_id;

not exists说:&#34;获取给定服务的历史记录,其中没有以后的历史记录。&#34;这相当于获得最后一个。