Question

When I do a SELECT statement with an AS definement and i want to filter on that it give the folowing error: #1054 - Unknown column 'TimeInSeconds' in 'where clause'

Code:

Select Id, time/10000000 as TimeInSeconds FROM Results WHERE
TimeInSeconds > 5 AND
TimeInSeconds < 36000

I understand the error that TimeInSeconds is not part of the original table, but are there ways to work with these defined collumns?

Was it helpful?

Solution

You can also use HAVING clause to filter out the results of custom aliases

Select Id, `time`/10000000 as TimeInSeconds 
FROM Results 
HAVING TimeInSeconds > 5 AND TimeInSeconds < 36000

Or repeat the expression using WHERE clause

Select Id, `time`/10000000 as TimeInSeconds 
FROM Results 
WHERE (`time`/10000000) > 5 AND (`time`/10000000) < 36000

OTHER TIPS

One option is to put the results in a subquery:

Select Id, timeinseconds
From (Select Id, time/10000000 as TimeInSeconds FROM Results) t
Where TimeInSeconds > 5 AND TimeInSeconds < 36000

The most efficient way to do this is:

select id, time/10000000 TimeInSeconds
from results
where time > 5 * 10000000
and time < 36000 * 10000000

The reason is the your field is being compared directly to values. The subquery method selects the whole darn table before filtering the results. Doing math on a field in the where clause, like using formulas, tends to be slow.

This is even more significant if the field in question is indexed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top