2011-12-09 138 views
2

我有一個現有的SQL查詢在SQL Server中正常工作,我想在MySQL中工作。我把它清理了一下,用列表/表格名稱等的後退標記來擺弄,但無法使其工作。mySQL中的嵌套select語句

這裏是有問題的聲明:

SELECT `EmployeeID` 
FROM `Employee` 
WHERE 
(
    (
     SELECT COUNT(*) AS A 
     FROM `TimeClock` 
     WHERE (`EmployeeID` = `Employee.EmployeeID`) 
     AND (`InOut` = 'True') 
    ) > (
     SELECT COUNT(*) AS B 
     FROM `TimeClock` AS `TimeClock_1` 
     WHERE (`EmployeeID` = `Employee.EmployeeID`) 
     AND (`InOut` = 'False') 
    ) 
) 

這應該返回必須在TimeClock表的詳細InOut = True超過InOut = False任何EmployeeID的。

謝謝。

+1

你得到的錯誤是什麼? – Zohaib

+0

Error'Unknown column'Employee.EmployeeID'in'where clause'' – Fuginator

回答

1

這應該爲您提供那裏是InOut真不是假

SELECT e.EmployeeId 
FROM Employee AS e 
INNER JOIN 
(
    SELECT tc.EmployeeID 
     , SUM(CASE 
       WHEN tc.InOut = 1 THEN 1 ELSE 0 
      END) AS InOutTrue 
     , SUM(CASE 
       WHEN tc.InOut = 0 THEN 1 ELSE 0 
      END) AS InOutFalse 
    FROM TimeClock AS tc 
    GROUP BY tc.EmployeeId 
) AS t ON e.EmployeeId = t.EmployeeId 
WHERE t.InOutTrue > t.InOutFalse 

我在我的很小沒有索引的測試數據顯示出類似的性能提出了兩個備選方案更值EmployeeId值。我建議你根據自己的數據對它們進行測試,看看它們是否有任何區別:

這一個是幾乎相同,但使用總記錄數而不是InOutFalse。

SELECT e.EmployeeId 
FROM Employee AS e 
INNER JOIN 
(
    SELECT tc.EmployeeID 
     , COUNT(1) AS RecordCount 
     , SUM(CASE 
       WHEN tc.InOut = 1 THEN 1 ELSE 0 
      END) AS InOutTrue 
    FROM TimeClock AS tc 
    GROUP BY tc.EmployeeId 
) AS t ON e.EmployeeId = t.EmployeeId 
WHERE t.InOutTrue > RecordCount - t.InOutTrue 

我不知道如果MySQL需要我這裏使用的CAST,但SQL Server一樣。 (這是我測試過的)它不能在BIT列上執行SUM

SELECT e.EmployeeId 
FROM Employee AS e 
INNER JOIN TimeClock AS tc ON e.EmployeeId = tc.EmployeeId 
GROUP BY e.EmployeeId 
HAVING SUM(CAST(tc.InOut AS INT)) > (COUNT(1) - SUM(CAST(tc.InOut AS INT))) 

如果三者的表現相似,則歸結爲個人偏好。

+0

Humm,我得到零行回到一張表,我知道EmployeeID 1有更多的InOut的真實比假...(樣本數據有10個True,9假) – Fuginator

+0

減少上面的代碼只是內部選擇,並運行返回employeeid的零爲bock InOutTrue和InOutFalse,如果這有幫助... – Fuginator

+0

@Fuginator什麼是InType的DataType?它實際上是一個字符串,還是一個布爾?另外,還有其他的InOut值是否比True或False? –