为什么这不起作用?
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`
基本上我要做的就是选择除了GROUP BY之外的MAX ... 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`
答案 0 :(得分:1)
在CREATE TABLE
查询中,您必须为MAX()
聚合列提供别名:
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`
你完成它的方式,列名应该类似于整个字符串MAX(ACCESS_DATE_TIME)
,这显然非常令人困惑。
现在,您可以按照尝试进行查询:
/* 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`
答案 1 :(得分: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`;