有表Table1、Table2、Table3各有不同的表结构,现在想要联合查询其中的部分字段。
例:
select 
    T1.ta,T1.tb,T2.tb,T3.tb,T2.tc 
From
    T1,T2,T3 
Where
    T1.ta=T2.ta and T2.tb=T3.tb问题:条件中T2.tb=T3.tb实际上是不固定的,就是说T2.tb=什么取决于记录中T1.tc的值(T1.tc可能取值为tc1或tc2,如果tc取值为tc1则T2.tb=T3.tb作为条件,否则T2.tb=T1.tb作为条件),T1.tc不作为查询结果。应该如何提前判断T1.tc的值呢?

解决方案 »

  1.   

    用动态sql或者case when咯。
      

  2.   

    select 
        T1.ta,T1.tb,T2.tb,T3.tb,T2.tc ,
        case when ta.tc='tc1'  then t3.tb else t1.tb end aa            
    From
        T1,T2,T3 
    Where
        T1.ta=T2.ta and 
        t2.tb=aa
      

  3.   

    谢谢两位了,我先试试。
    问个问题:case when 的返回值会作为一个列显示在查询结果中吗?
      

  4.   

    case when 的返回值会作为一个列显示在查询结果中吗?
    答案是是的
      

  5.   

    可不可以把“case when ta.tc='tc1'  then t3.tb else t1.tb end aa”
    直接写到Where语句中?
    像这样:
    t2.tb=(case when ta.tc='tc1'  then t3.tb else t1.tb end aa)