doudouwen2763 2015-10-23 10:38
浏览 70
已采纳

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

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 2015-10-23 11:30
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块