2017-01-21 124 views
-1

這裏有4個表....如何優化此sql查詢?

  1. tbl_std_working_hour
  2. tbl_attendance
  3. tbl_holiday
  4. tbl_leave

我想找出這個查詢員工缺勤報告... 。但是,當我爲許多員工應用此功能時,需要時間......有什麼方法可以簡化此查詢?

SELECT date 
FROM tbl_std_working_hour 
WHERE date NOT IN (SELECT date FROM tbl_attendance WHERE emp_id = '$emp_id') 
AND date NOT IN (SELECT date FROM tbl_holiday) 
AND date NOT IN (SELECT date FROM tbl_leave WHERE emp_id = '$emp_id') 
AND total_hour <> '00:00:00' 
AND date >= '$start' 
AND date <= '$end' 
AND emp_id = '$emp_id' 
+0

見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for什麼似乎對我來說是一個非常簡單的SQL查詢 – Strawberry

回答

2

首先,我的rewrite使用NOT EXISTS

SELECT wh.date 
FROM tbl_std_working_hour wh 
WHERE NOT EXISTS (SELECT 1 
        FROM tbl_attendance a 
        WHERE a.date = wh.date AND a.emp_id = wh.emp_id 
       ) AND 
     NOT EXISTS (SELECT 1 
        FROM tbl_holiday h 
        WHERE h.date = wh.date 
       ) AND 
     NOT EXISTS (SELECT 1 
        FROM tbl_leave l 
        WHERE l.emp_id = wh.emp_id and l.date = wh.date 
       ) 
WHERE wh.total_hour <> '00:00:00' AND 
     wh.date >= '$start' AND 
     wh.date <= '$end' AND 
     wh.emp_id = '$emp_id'; 

然後添加以下的複合(多列)的索引:

  • tbl_std_working_hour(emp_id, date, total_hour)
  • tbl_attendance(emp_id, date)
  • tbl_holiday(date)(可能已經如果存在是date主鍵或唯一)
  • tbl_leave(emp_id)(可能已經存在,如果emp_id是主鍵或唯一)

注意,我改變了查詢,以便參考emp_id外部查詢。這使得更容易更改emp_id。另外,您的查詢應該使用WHERE子句中的值的參數。

+1

它不工作..... !! :( – Kabir

+0

@Kabir ......「不工作」比較模糊,你應該對這個問題更加具體。 –

0

這也是一種更好的方式,可以更好地利用工作UNION ALL

SELECT date 
FROM tbl_std_working_hour AS tswh 
WHERE NOT EXISTS(
    SELECT date FROM tbl_attendance ta WHERE ta.date = tswh.date AND ta.emp_id = tswh.emp_id 
    UNION ALL 
    SELECT date FROM tbl_holiday th WHERE th.date = tswh.date 
    UNION ALL 
    SELECT date FROM tbl_leave tl WHERE tl.date = tswh.date AND tl.emp_id = tswh.emp_id) 
AND total_hour <> '00:00:00' 
AND date >= '$start' 
AND date <= '$end' 
AND emp_id = '$emp_id' 
+0

tbl_holiday不包含emp_id .....所以它給出錯誤,如 #1054 - 未知列'th 'emp_id'in'子句' – Kabir

+0

更新請檢查 – Susang

+0

@Suraz ......實際上,union all並不好,因爲它可能會阻止在單個表上使用索引(在MySQL中)。 –