0

我有一个超长的复杂 mysql 查询,我可以在这里粘贴,但我认为这对我的问题没有帮助。基本上,我有一个子查询,有时会返回不止一行。当这种情况发生时,整个查询就会爆炸。所以我想做的是让子查询返回该列的正常结果,除非返回多行,然后在该列中输出一些指定的文本。有道理?

编辑:根据要求,我将发布我的大型查询。我可能这样做很困难,但是我花了很长时间才得到查询,所以我不知道从哪里开始重写它。

SELECT TIME_FORMAT(
       TIMEDIFF(
         (SELECT PunchDateTime
         FROM timeclock_punchlog tp
         WHERE PunchEvent = 'breakin'
         AND DATE(tp.PunchDateTime) = DATE(U.time)
         AND tp.EmpID = U.EmpID),
         (SELECT PunchDateTime
         FROM timeclock_punchlog tp
         WHERE PunchEvent = 'breakout'
         AND DATE(tp.PunchDateTime) = DATE(U.time)
         AND tp.EmpID = U.EmpID)), '%i min.') AS Lunch
       FROM ((SELECT `enter`.EmpID,
       `enter`.PunchDateTime AS `time`,
       DATE_FORMAT(`enter`.PunchDateTime, '%m-%d-%Y')
       AS 'Punch Date',
       TIMESTAMPDIFF(SECOND, `enter`.PunchDateTime, '2003-05-01 00:00:00')
       AS `delta`
       FROM timeclock_punchlog AS `enter`
       WHERE `enter`.`In-Out` = 1)
       UNION
       (SELECT `leave`.EmpID,
       `leave`.PunchDateTime AS `time`,
       DATE_FORMAT(`leave`.PunchDateTime, '%m-%d-%Y')
       AS 'Punch Date',
       -TIMESTAMPDIFF(SECOND, `leave`.PunchDateTime, '2003-05-01 00:00:00')
       AS `delta`
       FROM timeclock_punchlog AS `leave`
       WHERE `leave`.`In-Out` = 0)) AS U
               LEFT JOIN prempl pe ON u.EmpID = pe.prempl
      WHERE DATE(U.`time`) >= ?startDate
      AND DATE(U.`time`) < ?endDate
    GROUP BY date(U.`time`), EmpID
  ORDER BY U.EmpID, U.`time` ASC";

有时返回多于一行的部分是定义为“午餐”的查询。

4

1 回答 1

1

如果您的查询与此类似:

SELECT id, col1, col2, (SELECT somecol FROM yourtable WHERE ...)
FROM   anothertable
....

例如,您可以使用以下技巧:

SELECT id, col1, col2,
       CASE WHEN
         (SELECT COUNT(*) FROM (..your subquery..) AS s)>1 THEN 'specified text'
       ELSE
         (..your subquery..)
       END AS value_returned_by_your_subquery
FROM   anothertable
....

请在此处查看示例。

但是当一个查询开始变得有点过于复杂,或者当它需要一些像这样的肮脏技巧时,如果你真的需要这样做,通常最好再考虑一下,也许有更好更干净的方法,但没有看到实际查询我无法为您提供更多帮助:)

于 2013-11-14T20:27:18.613 回答