PostgreSQL中的case和测试布尔字段

6

首先,我正在运行PostgreSQL 8.2,并在pgAdmin上测试我的查询。

我有一张表格,其中包含一些字段,例如:

mytable(
  id integer,
  mycheck boolean,
  someText varchar(200));

现在,我想要一个类似于这样的查询:
 select id,
  case when mycheck then (select name from tableA)
       else (select name from tableB) end as mySpecialName,
  someText;

我尝试运行并得到了以下结果:

ERROR: CASE types character varying and boolean cannot be matched
SQL state: 42804

甚至尝试用以下方式欺骗PostgreSQL:

case (mycheck::integer) when 0 then

没有起作用。

所以,我的问题是:由于SQL没有if,只有case,那么我该如何使用布尔字段进行if操作?

2个回答

11

你的问题在于值的不匹配(thenelse 后面的表达式),而不在于断言(when 后面的表达式)。确保 select name from tableAselect name from tableB 返回相同的结果类型。 mycheck 应该是一个布尔值。

我在 PostgreSQL 9.0beta2 上运行了此查询,并且(除了必须将 from mytable 添加到 SELECT 语句中以及创建 tableAtableB 表之外),它没有产生任何类型错误。但是,当我运行以下命令时,我会得到与您描述的类似的错误消息:

select case when true
           then 1
           else 'hello'::text 
       end;

上述代码的输出结果为:

ERROR:  CASE types text and integer cannot be matched

0

我在 PostgreSQL 8 上成功地运行了这个程序:

select id,
 case when mycheck = true then (...)
      else (...),
 someText;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接