MYSQL如何获得两行数据之间的时差?

时间:2018-01-31 17:55:47

标签: mysql

我有一个充当各种时钟的数据库。每次员工进出时,都会创建一个新的时间戳行,用于记录员工,他们所在的工作,是否进出,以及时间。

我现在可以正常工作,只要他们在12小时内不会进出一次或多次,但我怎样才能改进我的代码,这样他们就可以进出多个工作岗位。一天?



SELECT
    CONCAT(employees.Fname, ' ', employees.Lname) AS name, 
    timeInData.jobPK, 
    timeInData.timestamp AS TimeIn, 
    timeOutData.timestamp AS TimeOut, 
    timeInData.TSPK,
    timeOutData.TSPK, 
    TIMEDIFF(timeOutData.timestamp, timeInData.timestamp) AS hours,
    ROUND((sec_to_time(TIME_TO_SEC(timeOutData.timestamp) - TIME_TO_SEC(timeInData.timestamp)) /10000 * employees.cost), 2) AS empcost
FROM
    (SELECT * FROM timestamps WHERE status = 1 AND jobPK=$job) AS timeInData
    LEFT JOIN (SELECT * FROM timestamps WHERE status = 0 AND jobPK=$job) AS timeOutData ON timeInData.jobPk = timeOutData.jobPk AND timeInData.employeePK = timeOutData.employeePK
    JOIN employees ON timeInData.employeePK = employees.employeePK
WHERE
    timeOutData.timestamp BETWEEN timeInData.timestamp AND date_add(timeInData.timestamp, INTERVAL 720 MINUTE)
ORDER BY
    name ASC, TimeIn ASC;




现在,如果一天有4个时间戳,则每次进入并减去每次超时时间,导致数据行太多。这有什么解决方案吗?或者甚至只是一些其他文章可以帮助回答我的问题。我没有运气地浏览互联网。

由于

1 个答案:

答案 0 :(得分:0)

如果你想要一个纯粹的SQL解决方案,我会尝试围绕这些方面:

SELECT
    e.*,
    ti.timestamp AS TimeIn,
    to.timestamp AS TimeOut
FROM employees AS e
JOIN timestamps AS to
    ON to.employeePK = e.employeePK
    AND to.jobPK = $job
    AND to.status = 0
JOIN timestamps AS ti
    ON ti.employeePK = e.employeePK
    AND ti.jobPK = $job
    AND ti.timestamp = (
        SELECT MAX(ts.timestamp)
        FROM timestamps AS ts
        WHERE ts.employeePK = e.employeePK
        AND ts.jobPK = $job
        AND ts.status = 1
    )
    AND ti.status = 1

但在我看来,处理这样的时间序列并不属于关系代数。我宁愿使用存储过程创建游标(迭代员工)和临时表(包含运行总和)。或者甚至用相同的想法将所有计算都用于编程语言。有了employeePK,可以很容易地选择过去12小时内的所有条目,并在编程语言的一边处理它们。