计算上周的小时数

时间:2018-06-05 13:24:59

标签: php mysql sql mysqli pdo

我目前有一个时钟日志表,它引用了另外两个表。它引用的一个表包含时钟记录和另一个时钟记录:每个都有一个唯一的ID。

例如(对于每个rwh_clock_inrwh_clock_out表):

id 1
atTime 2018-06-05 14:01:38
userid 1

然后在时钟日志(rwh_clocking)内:

id 1
clockInId 1
clockOutId 1
hours 8

我正在尝试使用上周二strtotime('last tuesday')和下周二strtotime('next tuesday')来计算雇主在该周内完成的工作时间。

我正在使用PDO::Prepare(),日期位于< >期间,然后用户ID被放入我为哪个用户计算最近一周的小时数对

到目前为止,我有这个:

SELECT * 
FROM rwh_clocking 
WHERE ( CASE WHEN cio.ci > ? 
        AND cio.co < ? ) 
        FROM ( SELECT ? AS id, 
             ( SELECT atTime FROM rwh_clock_in WHERE userid = id ) AS 'ci',
             ( SELECT atTime FROM rwh_clock_out WHERE userid = id ) AS 'co' ) cio;

但是,这会在CASE中引发错误。任何帮助将不胜感激。

我想要的输出是:

id clockInId clockOutId hours
1  1         1          8
2  2         2          4
etc..

当clock_in和clock_out atTime介于上周二和下周二之间时。

我也尝试过:

SELECT clock.*, ( CASE WHEN cio.ci > ? AND cio.co < ? )
FROM rwh_clocking clock, ( SELECT ? AS 'id', 
    ( SELECT atTime FROM rwh_clock_in WHERE userid = id ) AS 'ci',
    ( SELECT atTime FROM rwh_clock_out WHERE userid = id ) AS 'co' ) cio;

我收到一个SQL错误:子查询返回超过1行当我运行它时:

SELECT c.clockInId, c.clockOutId, c.hours, cio.*
FROM rwh_clocking c,
    ( SELECT 1 as 'id',
        ( SELECT atTime FROM rwh_clock_in WHERE atTime > NOW() ) AS 'ci',
        ( SELECT atTime FROM rwh_clock_out WHERE atTime < NOW() ) AS 'co' ) cio;

所以我认为我需要在执行CASE之前遍历每个子查询。有什么想法吗?

更新

SELECT c.clockInId, c.clockOutId, c.hours
FROM rwh_clocking c,
    ( SELECT 1 as 'id',
        ( SELECT atTime FROM rwh_clock_in WHERE atTime > NOW() - INTERVAL 5 MINUTE AND userid = id ) AS 'ci',
        ( SELECT atTime FROM rwh_clock_out WHERE atTime < NOW() AND userid = id ) AS 'co' ) cio;

现在返回所有数据,但没有考虑时间。

*更新:**

现在,当它们存在时,它们不会返回任何行。

SELECT c.clockInId, c.clockOutId, c.hours
FROM rwh_clocking c,
    ( SELECT 2 as 'id',
        ( SELECT id FROM rwh_clock_in WHERE atTime > NOW() - INTERVAL 60 MINUTE AND userid = id ) AS 'ci',
        ( SELECT id FROM rwh_clock_out WHERE atTime > NOW() + INTERVAL 5 MINUTE AND userid = id ) AS 'co' ) cio
WHERE c.clockInId = cio.ci AND c.clockOutId = cio.co

1 个答案:

答案 0 :(得分:1)

您不需要所有CASE表达式和子查询。使用两个连接(使用三个命名参数useridtimeintimeout):

SELECT c.*
FROM
    rwh_clocking AS c
INNER JOIN rwh_clock_in AS ci
    ON c.clockInId = ci.id AND ci.userid = :userid
INNER JOIN rwh_clock_out AS co
    ON c.clockOutId = co.id AND co.userid = :userid
WHERE ci.atTime > :timein AND co.atTime < :timeout

Live fiddle