doudouwen2763
doudouwen2763
2015-10-23 10:38

在查询中使用多个条件时出错

已采纳

I am working with PostgreSQL 8.4.4. I want to fetch record from table based on multiple conditions as,

1) check if record exists

2) if exists then -> if type_id is 1 then select name if type_id is 2 then select name, abbreviation

3) if record not exits then print as 'Missing'

Following is the query for the same

select 
    case 
        when exists (select NAME || ' ' || ABBREVIATION from CONTACTS_COMPANY where id = 15)
        then ( select
                case
                    when type_id = '1' 
                        then (select UPPER(NAME) from CONTACTS_COMPANY where id = 15) 
                    when type_id = '2' 
                        then (select UPPER(NAME) || ' ' || UPPER(ABBREVIATION) from CONTACTS_COMPANY where id = 15) 
                end
            ) 
    else UPPER('MISSING')
end

When firing above query I am getting error as

SQL error:

ERROR: column "type_id" does not exist

LINE 7: when type_id = '1'

I am not getting what exactly is causing error. Any help would be appreciated. Thanks in advance!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanlieshuang5330 duanlieshuang5330 6年前

    Assuming that "type_id" does in fact exist (you probably made sure of that..?), I would say that the query is not structured correctly. Your outermost select misses a "from" - statement. Furthermore, your inner statements are not correct. It should look something like this:

    select 
        case 
            when exists  
               (select ('NAME' || ' ' || 'ABBREVIATION')
               from "CONTACTS_COMPANY")
            then (
                case
                    when type_id = '1' 
                        then UPPER("NAME") 
                    when type_id = '2' 
                        then  UPPER("NAME") || ' ' || UPPER("ABBREVIATION") 
                end
            ) 
    
        else UPPER('MISSING')
        end
    from "CONTACTS_COMPANY"
    WHERE id='15'
    

    I haven't tested this, but the general structure should be ok. And I have hopefully understood correctly, what you are trying to do. Please post a comment, if that is not so :)

    UPDATE code to working solution

    点赞 评论 复制链接分享

相关推荐