我有一个真正的用例,它需要在“where”子句中引用列别名。我正在尝试使用此处概述的技术,我希望这些技术适用于 Sybase 和 MySQL,但似乎不适用于 H2 或 HSQLDB: http ://databases.aspfaq.com/database/how-do-i -use-a-select-list-alias-in-the-where-or-group-by-clause.html
如果您愿意尝试重新创建我的问题,请执行以下操作:
create table CUSTOMER (code varchar(255), description varchar(255), active bit, accountOpeningDate date, currentBalance numeric(20,6), currentBalanceDigits int)
insert into CUSTOMER (code, description, active, accountOpeningDate, currentBalance, currentBalanceDigits) values ('BMW', 'BMW Motors', 0, '2011-01-01', 345.66, 2)
insert into CUSTOMER (code, description, active, accountOpeningDate, currentBalance, currentBalanceDigits) values ('MERC', 'Mercedes Motors', 1, '2012-02-02', 14032, 0)
然后,此 SQL 查询失败:
select nest.* from (
select CODE "id", DESCRIPTION "description",
ACTIVE "active",
accountOpeningDate "accountOpeningDate",
currentBalance "currentBalance"
from customer
) as nest
where nest.id = 'BMW'
如果您去掉“where nest.id = 'BMW'”就可以了。但是,如果尝试在 where 子句或 select 子句(nest.id 而不是 next.*)中使用任何别名,则查询会失败。错误代码是未找到列“NEST.ID”;... [42122-167] 42S22/42122
如果您尝试使用别名列名创建视图,然后尝试从视图中选择,则会发生同样的失败。例如:
create view customer_view as
select CODE "id", DESCRIPTION "description",
ACTIVE "active",
accountOpeningDate "accountOpeningDate",
currentBalance "currentBalance"
from customer
然后:
select id from customer_view