Florius
Florius

Reputation: 125

Use a select result and compare it

My question:

How do I get MySQL to use in a select a previouly selected value without repeating itself

My Answer, taken from another post

Set a variable direclty on the SELECT like this:

SELECT @q:= ##longQuery## AS a, (@q>2) AS b;

I had this MySQL:

SELECT ##longQuery## AS a, (a>2) AS b;

but I got:

ERROR 1054 (42S22): Unknown column 'a' in 'field list'

I didn't want to repeat the ##longQuery##, because it is actually quite lengthy on the real code.

Thank you

Upvotes: 1

Views: 295

Answers (2)

Matt Busche
Matt Busche

Reputation: 14333

Using a subQuery will work

SELECT a, (a>2) AS b
FROM (
  SELECT 1 AS a
) f

Upvotes: 0

Barranka
Barranka

Reputation: 21047

Two possible solutions:

  1. Use a subquery
  2. Use a variable

The subquery solution

select a, a>2 as b
from (select 1 as a) as q;

The 'variable' solution

set @a = 1;
select @a as a, @a>2 as b;

Upvotes: 2

Related Questions