我不明白为什么mysql说where子句中有未知的列。如果我删除别名并只使用log_archive.date,那么它可以正常工作。
这是sql:
SELECT DISTINCT(log_archive.msisdn) AS msisdn,
DATE(log_archive.date) AS actionDate,
users.activation_date
FROM log_archive
INNER JOIN users on log_archive.msisdn = users.msisdn
WHERE log_archive.action = 'pokrenuta aplikacija' AND
actionDate BETWEEN ':start_date' AND ':end_date'
ORDER BY actionDate DESC
以下是错误消息:
'where子句'
中的未知列'actionDate'
MySQL版本是5.1.36。
答案 0 :(得分:4)
列别名不能用于WHERE
子句。
http://dev.mysql.com/doc/refman/5.7/en/problems-with-alias.html
标准SQL不允许在WHERE子句中引用列别名。 强制执行此限制是因为WHERE子句是 评估后,列值可能尚未确定。对于 例如,以下查询是非法的:
答案 1 :(得分:1)
因为actionDate不是列的别名,actionDate是函数DATE
的结果的别名
如果更改sql如下,它仍然有效,所以问题不是别名,你必须使用where子句中的确切列。
SELECT DISTINCT(log_archive.msisdn) AS msisdn,
log_archive.date AS actionDate,
users.activation_date
FROM log_archive
INNER JOIN users on log_archive.msisdn = users.msisdn
WHERE log_archive.action = 'pokrenuta aplikacija' AND
DATE(actionDate) BETWEEN ':start_date' AND ':end_date'
ORDER BY actionDate DESC
答案 2 :(得分:0)
列别名不能在WHERE
子句中使用。您可以将该逻辑移动到派生表中:
SELECT DISTINCT msisdn, actionDate, activation_date
FROM
(
SELECT log_archive.msisdn AS msisdn,
DATE(log_archive.date) AS actionDate,
users.activation_date AS activation_date
FROM log_archive
INNER JOIN users on log_archive.msisdn = users.msisdn
WHERE log_archive.action = 'pokrenuta aplikacija'
) dt
WHERE actionDate BETWEEN ':start_date' AND ':end_date'
ORDER BY actionDate DESC
或者,仅限MySQL用户,在HAVING
子句中具有列别名条件。
或者只是将DATE(log_archive.date) BETWEEN ...
放在WHERE
子句中。
答案 3 :(得分:0)
列别名不能在WHERE子句中使用。而是可以使用Having子句。
SELECT DISTINCT
(log_archive.msisdn) AS msisdn,
DATE(log_archive.date) AS actionDate,
users.activation_date
FROM
log_archive
INNER JOIN
users ON log_archive.msisdn = users.msisdn
WHERE
log_archive.action = 'pokrenuta aplikacija'
having actionDate BETWEEN ':start_date' AND ':end_date'
ORDER BY actionDate DESC
您也可以通过
来完成SELECT DISTINCT
(log_archive.msisdn) AS msisdn,
DATE(log_archive.date) AS actionDate,
users.activation_date
FROM
log_archive
INNER JOIN
users ON log_archive.msisdn = users.msisdn
WHERE
log_archive.action = 'pokrenuta aplikacija' AND DATE(log_archive.date) BETWEEN ':start_date' AND ':end_date'
ORDER BY actionDate DESC