mySQL中嵌套的select语句

时间:2011-12-09 07:35:08

标签: mysql sql

我有一个在SQL Server中运行良好的SQL查询,我想在MySQL中工作。我已经把它清理了一下,然后摆弄了列/表名等的后退,但却无法使它工作。

以下是有问题的陈述:

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')
   )
)

这应该返回EmployeeID表中InOut = TrueInOut = FalseTimeClock的所有{{1}}。

感谢。

1 个答案:

答案 0 :(得分:1)

这应该为您提供EmployeeId值,其中InOut值的值为真{F}

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

我提出的两个替代方案在我的非常小的未编制索引的测试数据上表现出类似的性能。我建议你根据自己的数据对它们进行测试,看看它们是否有任何区别:

这个几乎相同,但使用总记录数而不是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确实如此。 (这是我测试过的内容)它无法在SUM列上执行BIT

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)))

如果三者的表现相似,则归结为个人偏好。