0

我有一个包含 4 个子查询的查询。查询是这样的:

SELECT
  (SELECT
     COUNT(id)
   FROM timelog
   WHERE emp_id = 1
       AND am_in > GET_TIME_IN1(emp_id, DATE)) AS tardy1,
  (SELECT
     COUNT(id)
   FROM timelog
   WHERE emp_id = 1
       AND pm_in > GET_TIME_IN2(emp_id, DATE)) AS tardy2,
   (SELECT balance FROM leave_credit lc JOIN leave_type lt ON lc.leave_type_id = lt.id WHERE emp_id = 1 AND lt.active = TRUE) AS balance,
   (SELECT leave_type_id FROM leave_credit lc JOIN leave_type lt ON lc.leave_type_id = lt.id WHERE emp_id = 1 AND lt.active = TRUE) AS leave_type_id

我这样做是为了让我只有 1 个从 PHP 到 SQL 服务器的查询字符串,并在一个实例中获取所有结果。我知道子查询会影响性能,但在我的情况下,有没有更好的方法来解决我的问题?

示例数据:时间日志表 时间记录表

离开信用表

留下信用

4

1 回答 1

1

这是一个替代版本:

SELECT tardy1, tardy2, balance, leave_type_id
FROM (SELECT emp_id, SUM(case when GET_TIME_IN1(emp_id, DATE) then 1 else 0 end) as tardy1,
             SUM(case when pm_in > GET_TIME_IN2(emp_id, DATE) then 1 else 0 end) as tardy2
      FROM timelog
      WHERE emp_id = 1 
      group by emp_id
     ) tardy join
    (SELECT emp_id, balance, leave_type_id
     FROM leave_credit lc full outer JOIN
          leave_type lt
          ON lc.leave_type_id = lt.id
     WHERE emp_id = 1 AND lt.active = TRUE
    ) balance
    on tardy.emp_id = balance.emp_id
where tardy.emp_id = 1 

对于所有员工:

SELECT tardy1, tardy2, balance, leave_type_id
FROM (SELECT emp_id, SUM(case when GET_TIME_IN1(emp_id, DATE) then 1 else 0 end) as tardy1,
             SUM(case when pm_in > GET_TIME_IN2(emp_id, DATE) then 1 else 0 end) as tardy2
      FROM timelog
      group by emp_id
     ) tardy full outer join
    (SELECT emp_id, balance, leave_type_id
     FROM leave_credit lc JOIN
          leave_type lt
          ON lc.leave_type_id = lt.id
     WHERE lt.active = TRUE
    ) balance
    on tardy.emp_id = balance.emp_id

如果您尝试组合这些子查询,则必须小心,因为 上有多个行timelog,并且员工可能在一个表中但不在另一个表中。

于 2013-01-04T14:47:40.173 回答