表:table
字段:A1 A2 A3
  值:11    33现在要查询table如果字段A1有值的话就把A1赋给result,如果A2有值的话就把A2赋给result,以此类推。希望高手们帮个忙谢谢。

解决方案 »

  1.   

    你这个result是变量还是一个表的字段?
    如果是变量的话这样:[code=SQL]
    select @result := if(not isnull(A1), A1, if(not isnull(A2), A2, A3))
    from table;若用在函数里也可以
    select if(not isnull(A1), A1, if(not isnull(A2), A2, A3)) into result
    from table;如果是字段的话这样:
    update result所在的表 set result = (select if(not isnull(A1), A1, if(not isnull(A2), A2, A3)) from table);
      

  2.   

    兄弟result只是个字段,不是变量
      

  3.   


    还有,其实我要的是搜索,如果A1包含搜索字段就返回A1,如果A2....以此类推,而且字段不是固定的,
    如果按照你写的这个if条件,如果有上10个字段的话那IF嵌套是不是太多了啊,有没有简单一点的?
      

  4.   

    select COALESCE(a1,a2,a3) from 表:table
      

  5.   

    谢谢,我搞定了,下面是我的代码
    $searchvar=",test1,test2,test3,"
        preg_match_all('/[^,]+/', $searchvar,$matches);//取出","号中的字段
    $s_result='';//查询包含搜索字符的字段
    $s_field='';//所有查询的字段
    $s_where='';//查询条件
    foreach($matches[0] as $field){
    if(!$s_result){
    $s_result="''";   
    }
    $s_result=" IF($field like '%$keywords%',$field,$s_result)";//mysql if嵌套
    if($s_field){
      $s_field=$s_field.",".$field;
      $s_where=$s_where." or $field like '%$keywords%'";
    }else{
      $s_field=$field;
      $s_where="$field like '%$keywords%'";
    }
    }
    $sql="select $s_result as result from table where $s_where limit 10";
      

  6.   


    这个不错,mysql 本身逻辑处理比较复杂,用外部程序来完成这个过程会简单很多。