Can MySQL temporary variables be used in a WHERE clause?

Can MySQL use temporary variables in a statement WHERE?

For example, in the following query:

SELECT `id`, @var := `id` * 2 FROM `user`

@var successfully set twice to id

However, if I try to filter the result set to include only the results where @var is less than 10:

SELECT `id`, @var := `id` * 2 FROM `user` WHERE @var < 10

then I get no results.

How to filter results based on @var value?

+4
source share
2 answers

You need to assign an alias and check it in the sentence HAVING:

SELECT id, @var := id * 2 AS id_times_2
FROM user
HAVING id_times_2 < 10

: , , . :

SELECT id, id * 2 AS id_times_2
FROM user
HAVING id_times_2 < 10
+13

: MySQL WHERE?

. MySQL (, @var) WHERE.

, .

WHERE SELECT.

@var < 10 ; - , , TRUE.

, , , .

: @var?

. (, , .)

, @var; , @var.

, SELECT, HAVING . (: HAVING , WHERE, .)

, WHERE .

, , , @var; @var.

+2

Source: https://habr.com/ru/post/1547463/


All Articles