2010-06-22 115 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;