代码之家  ›  专栏  ›  技术社区  ›  Naveed

一个通用的单sql查询

  •  0
  • Naveed  · 技术社区  · 14 年前

    我有一张这样的桌子:

    id | roll_no | name
    ---------------------
     1 |   111   | Naveed
     2 |   222   | Adil
     3 |   333   | Ali 
    

    $fields = array( "id" , "roll_no" ) $values = array( "1,111", "2,222" );

    如果我有这样的数据:

    $fields = array( "id" ) $values = array( "2", "3" );

    这意味着我必须编写一个sql查询来从where(id!=2)和(id!= 3). 这意味着将获取第一条记录。

    问: 如何使用php编写一个通用的单查询,以便使用上述两个数据数组从表中获取数据。

    谢谢

    3 回复  |  直到 14 年前
        1
  •  3
  •   gianebao Charitha    14 年前
    select * from dummy where concat_ws (',', id, roll_no) not in ('1,111', '2,222')
    

    完整解决方案:

    $tableName = "test"; 
    $fields = array( "id" , "roll_no" );
    $values = array( "1,111", "2,222" );
    
    $fieldsStr = implode(',', $fields);
    $valuesStr = implode("','", $values);
    $sql = "SELECT * 
        FROM $tableName 
        WHERE concat_ws(',', $fieldsStr ) NOT IN ( '$valuesStr' )";
    
        2
  •  0
  •   Frankie    14 年前

    你可能永远都要爆炸 Array 并将值作为字符串传递到查询中( sprintf

    吸引我注意的一件事是 你总是用身份证 . ID是唯一字段还是主字段?如果是这样的话,请忘记roll\u no,因为使用ID查询会更快。

        3
  •  0
  •   Naveed    14 年前

    $tableName = "test"; 
    $fields = array( "id" , "roll_no" );
    $values = array( "1,111", "2,222" );
    
    $fieldsStr = implode(',', $fields);
    $valuesStr = implode("','", $values);
    
    // Get all records from remote table
    $sql = "SELECT * FROM $tableName WHERE concat_ws(',', $fieldsStr ) NOT IN ( '$valuesStr' )";