我有以下情况
SELECT
...
...
(
@var1 = MAX(IF(table1.name='Mod', table1.value, NULL))
@var2 = MAX(IF(table1.name='Man', table1.value, NULL))
CASE
WHEN @var1 IS NOT NULL && @var2 IS NOT NULL THEN @var1+"/"+@var2
WHEN @var1 IS NULL && @var2 IS NOT NULL THEN @var2
WHEN @var1 IS NOT NULL && @var2 IS NULL THEN @var1
ELSE NULL
END) AS "col44",
这在mysql控制台中引发了异常。
我们不能在一般的mysql选择查询中进行变量赋值吗?
答案 0 :(得分:1)
这个怎么样?
SELECT ...
, @var1 = MAX(IF(table1.name='Mod', table1.value, NULL))
, @var2 = MAX(IF(table1.name='Man', table1.value, NULL))
, CASE
WHEN @var1 IS NOT NULL && @var2 IS NOT NULL THEN @var1+"/"+@var2
WHEN @var1 IS NULL && @var2 IS NOT NULL THEN @var2
WHEN @var1 IS NOT NULL && @var2 IS NULL THEN @var1
ELSE NULL
END AS "col44"
请注意添加逗号和删除括号。
或者,您可以使用子查询。 (根据我的经验,当与聚合一起使用时,查询中的变量变得不可预测;这完全避免了变量。)
SELECT ...
, CASE
WHEN modMax IS NOT NULL && manMax IS NOT NULL THEN modMax+"/"+manMax
WHEN modMax IS NULL && manMax IS NOT NULL THEN manMax
WHEN modMax IS NOT NULL && manMax IS NULL THEN modMax
ELSE NULL
END AS "col44"
FROM (
SELECT ...
, MAX(IF(table1.name='Mod', table1.value, NULL)) AS modMax
, MAX(IF(table1.name='Man', table1.value, NULL)) AS manMax
...
) AS subQ
附加说明:注意modMax+"/"+manMax
;它最终会给你一个从modMax + 0 + manMax计算的整数,而不是字符串。