单个SQL查询 [英] A general single sql query
问题描述
我有一个这样的表:
id | roll_no | name
---------------------
1 | 111 | Naveed
2 | 222 | Adil
3 | 333 | Ali
如果我有这样的数据:
$fields = array( "id" , "roll_no" )
和$values = array( "1,111", "2,222" );
这意味着我必须编写一个sql查询来从其中(id!= 1和roll_no!= 111)和(id!= 2和roll_no!= 222)的表中获取记录.这意味着将提取第三条记录.
It means I have to write a sql query to get records from table where (id != 1 and roll_no != 111) and (id != 2 and roll_no != 222). It means 3rd record will be fetched.
如果我有这样的数据:
$fields = array( "id" )
和$values = array( "2", "3" );
这意味着我必须编写一个SQL查询来从其中(id!= 2)和(id!= 3)的表中获取记录.这意味着将提取第一条记录.
It means I have to write a sql query to get records from table where (id != 2) and (id != 3). It means 1st record will be fetched.
问::如何使用php编写一般的单个查询,以使用上述两个数据数组从表中获取数据.
Q: How to write a general single query using php to get data from table using above two data arrays.
谢谢
推荐答案
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' )";
这篇关于单个SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!