Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i use a "virtual column" in Where clause?

I have this query:

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

I tried to use the newVisitID column in the WHERE clause like this:

WHERE newVisitID <=5

This gives me the error:

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

Could anyone help me solve this?

like image 760
Sultanen Avatar asked Apr 06 '26 07:04

Sultanen


2 Answers

You can't reference aliases in the WHERE clause, but you can reference them in 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
like image 182
Barmar Avatar answered Apr 08 '26 20:04

Barmar


You can write out the case statement again, or the easier way is to wrap it and then filter the subquery:

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
like image 26
Joe Enos Avatar answered Apr 08 '26 20:04

Joe Enos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!