我可以在Where子句中使用“虚拟列”吗?

时间:2013-10-11 22:14:26

标签: mysql where

我有这个问题:

set @last_uid = 0;
set @last_tm = '00:00';
set @last_vid = 0;

SELECT v.*,
     CASE WHEN @last_uid = visitorid AND cast( @last_tm as datetime) >= subtime( timestamp, '01:00' )
     THEN 
          if( (@last_tm := timestamp ), @last_vid, @last_vid)
     ELSE 
          if( (@last_uid := visitorid) + (@last_vid := @last_vid+1) +(@last_tm := timestamp ),@last_vid, @last_vid )
     END  AS newVisitID

FROM visits v
ORDER BY timestamp DESC, visitorid

我尝试在WHERE子句中使用newVisitID列,如下所示:

WHERE newVisitID <=5

这给了我错误:

#1054 - Unknown column 'newVisitID' in 'where clause'

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:5)

您无法在WHERE子句中引用别名,但可以在HAVING中引用它们:

SELECT v.*,
     CASE WHEN @last_uid = visitorid AND cast( @last_tm as datetime) >= subtime( timestamp, '01:00' )
     THEN 
          if( (@last_tm := timestamp ), @last_vid, @last_vid)
     ELSE 
          if( (@last_uid := visitorid) + (@last_vid := @last_vid+1) +(@last_tm := timestamp ),@last_vid, @last_vid )
     END  AS newVisitID

FROM visits v
HAVING newVisitID <- 5
ORDER BY timestamp DESC, visitorid

答案 1 :(得分:2)

您可以再次写出case语句,或者更简单的方法是将其包装然后过滤子查询:

select * from
(
    SELECT v.*,
        CASE WHEN @last_uid = visitorid AND cast( @last_tm as datetime) >= subtime( timestamp, '01:00' )
             THEN if( (@last_tm := timestamp ), @last_vid, @last_vid)
             ELSE if( (@last_uid := visitorid) + (@last_vid := @last_vid+1) +(@last_tm := timestamp ),@last_vid, @last_vid )
        END  AS newVisitID
    FROM visits v
) x
WHERE x.newVisitID <= 5
ORDER BY x.timestamp DESC, x.visitorid

答案 2 :(得分:1)

认为你可以使用变量

SELECT v.*,
     @newVisitID := CASE WHEN @last_uid = visitorid AND cast( @last_tm as datetime) >= subtime( timestamp, '01:00' )
     THEN 
          if( (@last_tm := timestamp ), @last_vid, @last_vid)
     ELSE 
          if( (@last_uid := visitorid) + (@last_vid := @last_vid+1) +(@last_tm := timestamp ),@last_vid, @last_vid )
     END  AS newVisitID

FROM visits v
where @newVisitID <= 5
ORDER BY timestamp DESC, visitorid

如果您不想重复代码,请使用子查询。