1

我有这个查询:

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'

谁能帮我解决这个问题?

4

3 回答 3

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
于 2013-10-11T22:22:01.370 回答
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
于 2013-10-11T22:18:06.247 回答
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

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

于 2013-10-11T22:17:13.313 回答