mysql - 我可以在 Where 子句中使用 "virtual column"吗?

标签 mysql where-clause

我有这个问题:

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'

谁能帮我解决这个问题?

最佳答案

您不能在 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

关于mysql - 我可以在 Where 子句中使用 "virtual column"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19328080/

相关文章:

PHP/MySQL where/order 子句不对数据进行排序

t-sql - 条件/可选 where 语句

php - MYSQL 表对字段挑剔?

php - wamp 服务器错误 #2002 无法打开 phpMyAdmin

MYSQL如何将外部计算值输入到行中

c# - if-else 等效于通过 where 子句中的 linq-to-sql 查询 c#

powershell - 输出文件并保留格式

mysql last url id 始终为 0

java - 使用 LOAD DATA INFILE 时如何有选择地更新表中的列?

MySQL 如何获取每组的前 N ​​行