简体   繁体   中英

MySQL Subquery Alternative

I have a query that consist 4 sub-queries in it. The query is this:

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

I made it like that so that I would only have 1 query string from PHP to the SQL server and get all the result in a instance. I know sub-queries can affect performance but in my situation is there a better way to address my problem?

Sample Data: Timelog Table 时间记录表

Leave Credit Table

离开信用

Here is an alternative version:

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 

For all employees:

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

If you try to combine these subqueries, you have to be careful, because of the multiple rows on timelog , and the possiblity that employees are in one table but not the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM