Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select AS temp_name FROM table WHERE temp_name = something?

Tags:

mysql

You know how you can assign a temporary column name to a return value in a SQL statement like this?

SELECT something+this+that AS myvalue FROM mytable

Is it possible to use the temporary name myvalue as a conditional?

SELECT something+this+that AS myvalue FROM mytable WHERE myvalue = 10

I can't seem to figure out the syntax to do this. The only way I can figure out how to do it is to rewrite out the entire column definition again like this:

SELECT something+this+that AS myvalue FROM mytable WHERE something+this+that = 10

Obviously the above example is a trivial example. My query I need to do this on is extremely complexed, so having the rewrite each returned column definition for each conditional will be quite a hassle.

So anyways, what is the syntax for this? Is it possible?

like image 336
Jake Wilson Avatar asked Jun 20 '10 05:06

Jake Wilson


1 Answers

Use a derived table...

SELECT
    myvalue
FROM
    (
    SELECT something+this+that AS myvalue FROM mytable
    ) foo
WHERE
    myvalue = 10

Or use a CTE which looks more elegant but is the same

;WITh myCTE AS
(
    SELECT something+this+that AS myvalue FROM mytable
)
SELECT
    myvalue
FROM
    myCTE
WHERE
    myvalue = 10

Or a computed column so it's usable normally

ALTER TABLE MyTable ADD myvalue AS something+this+that
like image 109
gbn Avatar answered Sep 26 '22 05:09

gbn