2

我有一个真正的用例,它需要在“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
4

1 回答 1

5

问题是不带引号和带引号的标识符的混合使用。根据 SQL 规范,不带引号的标识符(例如id)不区分大小写,数据库可能会将它们转换为大写或小写。引号标识符(例如"id")区分大小写,并且数据库引擎不得转换标识符。

H2 converts unquoted identifiers to uppercase (like other database engines such as Oracle). In your query, you have used both quoted and unquoted identifiers. Simplied test case (fails for H2 and other databases):

select * from (select 1 "id") where id = 1

To solve the problem, you need to use either quoted identifiers everywhere, or unquoted identifiers:

select * from (select 1 id) where id = 1

or

select * from (select 1 "id") where "id" = 1
于 2012-06-22T17:57:09.350 回答