2010-06-22 116 views
5

第一:我正在运行postgresql 8.2并在pgAdmin上测试我的查询。Postgresql案例和测试布尔字段

我有一些字段的表,说:

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没有,如果,唯一的情况下,我如何设置如果与布尔字段?

回答

10

你的问题是你的值不匹配(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;