选择虚拟列不在where条件下工作

时间:2016-01-15 06:09:24

标签: php mysql sql

我尝试做的是在select中进行一些计算并将其指定为虚拟变量,如作为TimeDiff ,但是当我尝试在其所处的条件下使用它时未知专栏。

我尝试了两种方法都失败了:

1:

SELECT `AL`.`UserID`, ROUND(IFNULL(TIMESTAMPDIFF(SECOND, MIN(AL.CreatedDate), MAX(AL.CreatedDate)) / NULLIF(COUNT(*) - 1, 0), 0)) as TimeDiff FROM (`ActiveLogins` AL) LEFT JOIN `Users` U ON `U`.`UserID`=`AL`.`UserID` WHERE `U`.`StatusID` IN (1, 2) AND TimeDiff>0 AND TimeDiff<86401 GROUP BY `AL`.`UserID`

2:

SELECT `AL`.`UserID`, @TimeDiff := ROUND(IFNULL(TIMESTAMPDIFF(SECOND, MIN(AL.CreatedDate), MAX(AL.CreatedDate)) / NULLIF(COUNT(*) - 1, 0), 0)) as TimeDiff FROM (`ActiveLogins` AL) LEFT JOIN `Users` U ON `U`.`UserID`=`AL`.`UserID` WHERE `U`.`StatusID` IN (1, 2) AND @TimeDiff>0 AND @TimeDiff<86401 GROUP BY `AL`.`UserID`

在第二个查询中没有错误,但是没有记录返回但是表中存在记录,表中UserID和ActiveLogin表中的CreatedDate只有2列

2 个答案:

答案 0 :(得分:0)

您不能在同一Alias name个查询select子句中使用where。在外部查询中添加过滤器

SELECT *
FROM   (SELECT `al`.`userid`, 
               Round(Ifnull(Timestampdiff(second, Min(al.createddate), 
                            Max(al.createddate)) / 
                                  Nullif(Count(*) - 1, 0), 0)) AS timediff 
        FROM   `activelogins` al 
               LEFT JOIN `users` u 
                      ON `u`.`userid` = `al`.`userid` 
                     AND  `u`.`statusid` IN ( 1, 2 )) a 
WHERE  timediff > 0 
       AND timediff < 86401 
GROUP  BY `userid` 

这是逻辑处理查询的方式

1. FROM
2. ON
3. OUTER
4. WHERE
5. GROUP BY
6. CUBE | ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10 ORDER BY
11. TOP

正如您在SELECT子句后面看到的WHERE一样,您无法使用where中生成的select中的别名

答案 1 :(得分:0)

您需要对聚合列使用HAVING关键字

SELECT 
  `AL`.`UserID`, 
  ROUND(IFNULL(TIMESTAMPDIFF(SECOND, MIN(AL.CreatedDate), MAX(AL.CreatedDate)) / NULLIF(COUNT(*) - 1, 0), 0)) as TimeDiff 
FROM 
  (`ActiveLogins` AL) LEFT JOIN `Users` U ON `U`.`UserID`=`AL`.`UserID` 
WHERE 
  `U`.`StatusID` IN (1, 2) 
HAVING 
  TimeDiff>0 AND TimeDiff<86401 
GROUP BY 
  `AL`.`UserID`