如何在where子句中使用用户定义的变量

时间:2017-03-21 19:36:18

标签: mysql

我有这个查询,并且我试图在我的where子句中使用用户定义的变量@noVar来仅显示具有值的记录'是'在那个变量上。 但是当我使用@noVar ='是'如下面的查询,它返回0结果。

SELECT svcreqdetail.id, svcreqcheckin.stime as checkin, @etime:=     time(timestampadd(minute, svcreqdetail.hours*60 , concat(caredate,' ', caretime))) as endtime, svcreqcheckout.stime as checkout, time_to_sec( if(svcreqcheckout.stime > svcreqcheckin.stime,
          timediff(svcreqcheckout.stime, svcreqcheckin.stime),
          addtime(timediff(svcreqcheckout.stime, svcreqcheckin.stime), '24:00:00.000000')))/3600 AS wrkHrs, svcreqdetail.hours,
svcreqstatus.status, @checkoutvar:= time_to_sec(timediff(svcreqcheckout.stime, @etime))/60 as checkoutvar,@noVar:= if (@checkoutvar <= 15,'Yes', 'No') as noVar, qualif
FROM svcreqdetail
LEFT JOIN svcreqcheckin ON svcreqcheckin.reqid = svcreqdetail.id
LEFT JOIN svcreqcheckout ON svcreqcheckout.reqid = svcreqdetail.id
JOIN svcreqstatus ON svcreqstatus.reqdid = svcreqdetail.id
WHERE (yearweek( caredate ) = yearweek( date_sub( CURRENT_DATE, INTERVAL 1 week ) )
AND svcreqstatus.status != 'Incompleted'
AND svcreqstatus.status != 'Deleted')
having @noVar = 'Yes'

无论如何我可以在我的where子句中测试该变量。谢谢你

1 个答案:

答案 0 :(得分:0)

我认为您不能在HAVING子句中使用用户定义的变量。

一种选择是将现有查询(不带HAVING子句)放入子查询中,并使用子查询外的WHERE子句过滤结果,如下所示:

SELECT *
FROM
(
  <your existing query goes here>
) AS sub_query
WHERE noVar = 'Yes'