问题一 :表一:  table1  
表一字段: pid pfilename pvsum表二:  table2
表二字段:  tid pid tvendors
pid 为 表一 的主键 表二的外键现在我想查询出来的结果 pid pfilename pvsum  tishavetishave 为自定义字段,如果表一中的主键在表二中存在记录 那么这个字段显示为 :已存在
                      如果表一中的主键在表二中没有记录 那么这个字段显示为 :未存在
例如:
table1中记录     pid    pfilename    pvsum
      1      123.pdf      5
      2      234.doc      7table2 中记录     tid  pid  tvendors
       1   1      ZTE查询出结果为:
   
      pid   pfilename    pvsum    tishave
       1      123.pdf      5       已存在
       2      234.doc      7       未存在
问题二:
      如果表一种字段  pfilename  结果为NULL  在查询时我想让为NULL的显示为  空  该怎么做呵呵,小弟菜鸟...突然想到这两个问题,求解。 
   

解决方案 »

  1.   

    查询中的条件判断经常遇到在某些条件下应该查询这个字段,在另外一些条件下需要其他字段的情况,可以通过unoin来完成,但也可以通过CASE WHEN 完成/*在State=0 时返回field1 ,在State=1时返回 field2 ,其他时返回field3*/    SELECT (CASE WHEN   State=0 THEN field1 WHEN   State=1 THEN field2
        ELSE field3 END ) as State
        FROM tablename 
      

  2.   


    select pid ,pfilename ,pvsum,
    case when exists(select 1 from table2 where a.pid=pid) then 'exist' else 'not exist' end as tishave
    from table1  a 
      

  3.   


    select a.pid,isnull(a.pfilename,'空')pfilename,a.pvsum,
    case when b.num=0 then '未存在' else '已存在' end as tishave
    from table1 a
    left join
    (
    select pid,count(1)num from table2
    group by pid
    )b on a.pid=b.pid
      

  4.   

     select t1.pid, isnull(t1.pfilename,'空') pfilename, t1.pvsum
    ,(case  when (t2.pid IS null) then '未存在' else '已存在'end) tishave
      from table1 t1
     left join table2 t2 on t1.pid=t2.pid