3

为什么这不起作用?

SELECT `user_log`.`COMPUTER_NAME`, `user_log`.`LOCATION` 
FROM `user_log`, `user_log_max` as max
WHERE max.`USER_NAME` = `user_log`.`USER_NAME` AND max.`ACCESS_DATE_TIME` = `user_log`.`ACCESS_DATE_TIME`

我收到以下错误:

#1054 - Unknown column 'max.ACCESS_DATE_TIME' in 'where clause'

我试过去掉别名:

SELECT `user_log`.`COMPUTER_NAME`, `user_log`.`LOCATION` 
FROM `user_log`, `user_log_max`
WHERE `user_log_max`.`USER_NAME` = `user_log`.`USER_NAME` AND `user_log_max`.`ACCESS_DATE_TIME` = `user_log`.`ACCESS_DATE_TIME`

这个错误->

#1054 - Unknown column 'user_log_max.ACCESS_DATE_TIME' in 'where clause'

它正在去掉刻度线……为什么?

编辑:

user_log_max:
USER_NAME        varchar(20)      
ACCESS_DATE_TIME timestamp  

user_log 包含相同的列,以及更多的列,包括 COMPUTER_NAME 和 LOCATION

user_log_max 包含在 user_log 上发出此查询的所有数据

SELECT `USER_NAME`, MAX(`ACCESS_DATE_TIME`) FROM `user_log
GROUP BY `USER_NAME`

本质上,我要做的是选择具有 MAX...GROUP BY 的列,而不是我的 GROUP BY 中的列。

编辑2:

这是我创建 user_log_max 的方式->

 CREATE TABLE `user_log_max`
SELECT `USER_NAME`, MAX(`ACCESS_DATE_TIME`) FROM `user_log`
GROUP BY `USER_NAME`
4

2 回答 2

1

In your CREATE TABLE query, you must supply an alias for the MAX() aggregate column:

 CREATE TABLE `user_log_max`
   SELECT
     `USER_NAME`, 
      /* Alias this calculated value as ACCESS_DATE_TIME */
      MAX(`ACCESS_DATE_TIME`) AS `ACCESS_DATE_TIME` 
   FROM `user_log`
   GROUP BY `USER_NAME`

The way you had done it, the column name should be something like the whole string MAX(ACCESS_DATE_TIME), which is obviously very confusing.

Now, you can query it as you attempted to do:

/* The column ACCESS_DATE_TIME now exists in user_log_max, so this will work */
SELECT `user_log`.`COMPUTER_NAME`, `user_log`.`LOCATION` 
FROM `user_log`, `user_log_max`
WHERE `user_log_max`.`USER_NAME` = `user_log`.`USER_NAME` AND `user_log_max`.`ACCESS_DATE_TIME` = `user_log`.`ACCESS_DATE_TIME`
于 2012-09-28T16:31:34.640 回答
0

where将子句更改为on

SELECT `user_log`.`COMPUTER_NAME`, `user_log`.`LOCATION` 
FROM `user_log`, `user_log_max`
ON `user_log_max`.`USER_NAME` = `user_log`.`USER_NAME` AND `user_log_max`.`ACCESS_DATE_TIME` = `user_log`.`ACCESS_DATE_TIME`;
于 2017-05-13T13:52:07.827 回答