Answer the question
In order to leave comments, you need to log in
Query in MySQL
I have a query that calculates some value using CASE, for example:
SELECT (CASE WHEN a.id > 500 THEN a.id ELSE a.id + 500 END) as new_column FROM table a;
How to use new_column value to calculate one more value? Those. something like:
SELECT (CASE WHEN a.id > 500 THEN a.id ELSE a.id + 500 END) as new_column, (CASE WHEN new_column < 1000 THEN new_column ELSE new_column + 1000) as new_column2 FROM table a;
MySQL swears at such a request, says that Column not found: 1054 Unknown column 'new_column' in 'field list'
Answer the question
In order to leave comments, you need to log in
use full-length notation (CASE WHEN a.id > 500 THEN a.id ELSE a.id + 500 END) instead
of
new_column
into a character including register.
SELECT new_column, (CASE WHEN new_column < 1000 THEN new_column ELSE new_column + 1000 END) as new_column2 FROM (SELECT (CASE WHEN a.id > 500 THEN a.id ELSE a.id + 500 END) as new_column FROM table as a) as b
-- Not an efficient way, but acceptable on small samples B SELECT b.new_column, IF(B.new_column < 1000, B.new_column, B.new_column + 1000) AS new_column2 FROM( SELECT IF(a.id > 500, a.id, a.id + 500) as new_column FROM table a ) AS B; - And it can be... SELECT (a.id + IF(a.id < 500, 500, 0)) as new_column, (a.id + IF(a.id > 1000, 1000, 0)) as new_column2 FROM table a
Thanks for the answer. The fact is that the expression is quite long (5 lines), but since there is no other way out ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question