table listlistId listType
11111   01
22222   02
33333   03
44444   04table 01 
listId  listAA listBB
11111    x      x
table 02 
listId  listAA listBB
22222    y      y
table 03 
listId  listAA listBB
333333   xx     xx
table 04 
listId  listAA listBB
444444    yy      yy想查询如下 根据 list 表 的 listType 字段值 (01,02,03,04) 分别去关联 table01,table02,table03,table04 (关联条件 list.listid==01.listId)取得相应的listAA listBB 值SELECT 
       
       (case
         when listType = '01' then
          (select 01.listAA
             from 01
            where 01.listId = list.listId)
            
            when listType = '02' then
          (select 02.listAA
             from 02
            where 02.listId = list.listId)
            when listType = '03' then
          (select 03.listAA
             from 03
            where 03.listId = list.listId)
            
            when listType = '04' then
          (select 04.listAA
             from 04
            where 04.listId = list.listId)
         else
          ''
       end) AS listAA,  (case
         when listType = '01' then
          (select 01.listBB
             from 01
            where 01.listId = list.listId)
            
            when listType = '02' then
          (select 02.listBB
             from 02
            where 02.listId = list.listId)
            when listType = '03' then
          (select 03.listBB
             from 03
            where 03.listId = list.listId)
            
            when listType = '04' then
          (select 04.listBB
             from 04
            where 04.listId = list.listId)
         else
          ''
       end) AS listBB  FROM list这样相当于 取AA ,BB都查了一次,有什么方法可以写一次,返回两个字段 AA,BB 

解决方案 »

  1.   

    select t1.listAA,t1.listBB from list t,
    (select * from 01 union all select * from 02 union all select * from 03 union all select * from 04)t1
    where t.listid = t1.listid
      

  2.   

    ls 这是吧 01~ 04 先UNION 起来。但 01~04 是比较大的表。 LIST是比较小的表 ~,这样先把 01~04所有的值先查出来是不是比较慢~
      

  3.   

    select listAA,listBB
    from list ,01
    where list.listid=01.listid
    and list.listType='01'
    union all
    select listAA,listBB
    from list ,02
    where list.listid=02.listid
    and list.listType='02'
    union all
    select listAA,listBB
    from list ,03
    where list.listid=03.listid
    and list.listType='03'
    union all
    select listAA,listBB
    from list ,04
    where list.listid=04.listid
    and list.listType='04'