我有一个超长的复杂的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";
有时返回多行的部分是定义为“Lunch”的查询。
答案 0 :(得分: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
....
请参阅示例here。
但是当一个查询开始变得有点过于复杂,或者当它需要一些像这样的肮脏技巧时,如果你真的需要这样做,通常会更好地再思考一下,也许有更好更清洁的方式,但没有看到实际的查询,我无法帮助你更多:)