我正在尝试执行这样的查询:
SELECT
(17 + 4) AS foo,
foo * 2 AS bar;
失败,返回Unknown column 'foo' in 'field list'
。所以我这样做了:
SELECT
(@foo := 17 + 4) AS foo,
@foo * 2 AS bar;
哪个有效。现在的问题是我想在foo
子句中集成这个计算值(WHERE
):
SELECT
(@foo := 17 + 4) AS foo,
@foo * 2 AS bar
FROM lorem
WHERE foo = 21;
失败:Unknown column 'foo' in 'where clause'
。
如果我将foo
替换为@foo
中的WHERE
,则可行。但是,如果我用列替换文字,它就会停止工作:
SELECT
(@foo := ipsum) AS foo,
@foo * 2 AS bar
FROM lorem
WHERE @foo = 33;
在表lorem
中返回包含此内容的空集:
SELECT * FROM lorem;
+-------+
| ipsum |
+-------+
| 33 |
+-------+
答案 0 :(得分:3)
我找到了解决方案,它使用HAVING
子句代替WHERE
,如下所示:
SELECT
(@foo := ipsum * 2) AS foo,
@foo * 2 AS bar
FROM lorem
HAVING foo = 66;
返回:
+------+------+
| foo | bar |
+------+------+
| 66 | 132 |
+------+------+
使用:
SELECT * FROM lorem;
+-------+
| ipsum |
+-------+
| 33 |
| 41 |
+-------+
因为在HAVING
之后SELECT
评估了;虽然WHERE
子句在<{1}}之前评估,但在FROM
之后。
答案 1 :(得分:2)
子选择!
SELECT foo
, foo * 2 As bar
FROM (
SELECT (17 + 4) AS foo
) As hey_look_at_me
WHERE foo = 42
答案 2 :(得分:0)
我不知道你为什么要这样做,但这样做会。
选择 (@foo:= 17 + 4)AS foo, @foo:= @ foo * 2 AS吧; 从表 在哪里@foo = 42;
foo不是一个列,它是一个计算值,所以你不能在where子句中使用它。并且@foo在您的查询中的值为21,如果您说@foo = 42则会失败,因此它不会给出任何结果。
因此,如果您希望验证最终值,请将其分配给变量并验证它。
答案 3 :(得分:-2)
select * from table_temp;
foo bar
11 54
17 42
SELECT
17+4 AS foo,
foo * 2 AS bar
from table_temp
where bar =42;
foo bar
21 42