将子查询转换为加入的问题

时间:2016-01-05 18:36:13

标签: mysql join

我有一张时钟表,还有一张表,如果员工忘记上班/下班,则该表包含对时钟的调整。 timeclock(newclock)表的格式是这样的 -

ID

日期时间

事件(IN或OUT)

EMPLOYEE_ID

雇主

调整表(adjust_clock)是这样的 -

adjusted_shift(从newclock表中调整的移位ID)

new_dt

我有这个查询 -

SELECT 
    nc.id AS clockInId,nc.pin, nc.employee_id,(
        SELECT min(newclock.id) 
        FROM newclock 
        WHERE 
            newclock.id > clockInId AND
            employee_id=nc.employee_id AND event='OUT'
    ) AS clockOutId,
    IFNULL(ac.new_dt, nc.tod) as clockInTime,
    IFNULL(
        (
            SELECT new_dt FROM adjust_clock WHERE adjusted_shift=clockOutId
            ORDER BY id DESC LIMIT 1
        ), (
            SELECT tod FROM newclock WHERE
            newclock.id=clockOutId
        )
    ) AS clockOutTime
FROM newclock nc
LEFT JOIN 
    adjust_clock ac ON ac.adjusted_shift=nc.id
WHERE 
    nc.employer='122' AND (nc.tod) BETWEEN '2015-12-28 00:00:00' AND '2016-01-03 23:59:59'
    AND nc.event='IN'`

一切正常,它太慢了。任何人都可以建议一种加快速度的方法吗?杀死性能的线是这个 - IFNULL((SELECT new_dt FROM adjust_clock WHERE adjusted_shift=clockOutId ORDER BY id DESC LIMIT 1),(SELECT tod FROM newclock WHERE newclock.id=clockOutId)) AS clockOutTime

我试过把它放在这样的连接中,但没有运气 - LEFT JOIN (SELECT new_dt, adjusted_shift FROM adjust_clock ORDER BY id DESC LIMIT 1) adjustClockOut ON adjustClockOut.adjusted_shift=(SELECT min(newclock.id) FROM newclock WHERE newclock.id>nc.id AND nc.event='OUT' AND newclock.employee_id=nc.employee_id)

非常感谢任何建议或帮助!

0 个答案:

没有答案