Reputation: 431
I do not understand why mysql says that there is unknown column in where clause. If I remove alias and just use log_archive.date then it works just fine.
Here is the 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
Here is the error message:
Unknown column 'actionDate' in 'where clause'
MySQL version is 5.1.36.
Upvotes: 1
Views: 918
Reputation: 790
Because your actionDate is not a aliased name of column, actionDate is a aliase of the result of function DATE
If change the sql as below, it's still working, so problem is not the aliased name, you must use the exactly column in where clause.
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
Upvotes: 1
Reputation: 393
Column alias name can't be used in WHERE clause. Instead Having clause can be used.
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
You can also do it by
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
Upvotes: 0
Reputation: 44746
Column aliases can't be used in the WHERE
clause. You can move that logic into a derived table:
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
Or, MySQL users only, have the column alias condition in a HAVING
clause.
Or simply put DATE(log_archive.date) BETWEEN ...
in the WHERE
clause.
Upvotes: 0
Reputation: 6065
Column alias name can't be used in WHERE
clause.
http://dev.mysql.com/doc/refman/5.7/en/problems-with-alias.html
Standard SQL disallows references to column aliases in a WHERE clause. This restriction is imposed because when the WHERE clause is evaluated, the column value may not yet have been determined. For example, the following query is illegal:
Upvotes: 4