列别名不适用于 MySQL 中的 Group、Where 和 Having
Column alias is not working for Group, Where and Having in MySQL
我遇到了以下问题。
我想执行 as sql 语句,用 HAVING 过滤结果。然而,having 位于从 select 内的 IF() 函数计算的列上。这样,MySQL 服务器会抱怨 having 子句中的列未知!
EX:
SELECT col1,col2,IF(expr1,expr2,expr3) AS `wantedColumn`
FROM....
WHERE ...
HAVING LENGTH(`wantedColumn)>0
这是因为 mysql 无法理解 if 表达式返回的列名为 wantedColumn... 如果我使用其他列,它可以正常工作。但我需要对此进行过滤。有什么建议么?
谢谢
这是由于模式配置:
如果您的数据库使用模式'ONLY_FULL_GROUP_BY',您将无法在WHERE、GROUP BY 或HAVING 中使用列别名,它不起作用。您必须重复整个表达式或使用子查询。
为了知道您是否使用 'ONLY_FULL GROUP_BY' 模式,请使用以下查询:
SELECT @@sql_mode;
如果您想将其更改为允许它的模式:
SET SESSION sql_mode =STRICT_TRANS_TABLES;
要了解有关 SQL 模式的更多信息:
http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
Inanda Menezes @Inanda 的评论回答:
Look at it: sqlfiddle.com/#!2/5294e4/6 , I just removed the backticks
from the alias used inside the having and your example worked.
According to mysql documentation you don't need to use backticks on
identifiers that does not have special words or characters. If you use
it, in most of cases, it will not cause your query to fail, but it's
not necessary at all to quote normal identifiers with non-standard
escape. Anyway, it seems to fail when escaping with backsticks a alias
in having clause which uses length function, so just don't escape this
one. – Inanda Menezes
我遇到了以下问题。 我想执行 as sql 语句,用 HAVING 过滤结果。然而,having 位于从 select 内的 IF() 函数计算的列上。这样,MySQL 服务器会抱怨 having 子句中的列未知!
EX:
SELECT col1,col2,IF(expr1,expr2,expr3) AS `wantedColumn`
FROM....
WHERE ...
HAVING LENGTH(`wantedColumn)>0
这是因为 mysql 无法理解 if 表达式返回的列名为 wantedColumn... 如果我使用其他列,它可以正常工作。但我需要对此进行过滤。有什么建议么? 谢谢
这是由于模式配置:
如果您的数据库使用模式'ONLY_FULL_GROUP_BY',您将无法在WHERE、GROUP BY 或HAVING 中使用列别名,它不起作用。您必须重复整个表达式或使用子查询。
为了知道您是否使用 'ONLY_FULL GROUP_BY' 模式,请使用以下查询:
SELECT @@sql_mode;
如果您想将其更改为允许它的模式:
SET SESSION sql_mode =STRICT_TRANS_TABLES;
要了解有关 SQL 模式的更多信息: http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html
Inanda Menezes @Inanda 的评论回答:
Look at it: sqlfiddle.com/#!2/5294e4/6 , I just removed the backticks from the alias used inside the having and your example worked. According to mysql documentation you don't need to use backticks on identifiers that does not have special words or characters. If you use it, in most of cases, it will not cause your query to fail, but it's not necessary at all to quote normal identifiers with non-standard escape. Anyway, it seems to fail when escaping with backsticks a alias in having clause which uses length function, so just don't escape this one. – Inanda Menezes