如何改进以下mySql查询以使用PDO预处理语句?

时间:2016-07-28 23:36:12

标签: mysql sql pdo

我有一个表“my_table”,其中包含以下字段

object_id: number | object_type: varchar | object_value: text

示例数据:

4 | post | Lorem ipsum
2 | file | Lorem ipsum
3 | post | Lorem ipsum
2 | page | Lorem ipsum
1 | post | Lorem ipsum
2 | file | Lorem ipsum

我有一个包含object_id和object_types的对象数组。有没有更好的方法来执行以下查询,如果是这样,它将如何在PDO预处理语句中查看?

SELECT *
FROM my_table
WHERE (object_id = 4 AND object_type = 'post')
OR (object_id = 2 AND object_type = 'file')
OR (object_id = 3 AND object_type = 'post');

感谢任何响应者

3 个答案:

答案 0 :(得分:3)

这将有效(object_id, object_type) IN ((4, 'post'), (2, 'file'), (3, 'post'))

如果in列表中的元组数量不同,您需要动态构建您提供给PDO的查询(以及参数列表)。

答案 1 :(得分:2)

这是一个选项:

select * from mytable
where (object_id, object_type) in (
    select 4, 'post' union all 
    select 2, 'file' union all 
    select 3, 'post')

或者

select * from mytable
where (object_id, object_type) in ((4, 'post'), (2, 'file'), (3, 'post'))

答案 2 :(得分:1)

非常感谢上面的人提供他们的答案。您已帮助我提出以下动态PDO准备语句。

// THIS IS MY ARRAY OF OBJECTS
$data[0]['object_id']=4;
$data[0]['object_type']='post';
$data[1]['object_id']=2;
$data[1]['object_type']='file';

// CREATING A DYNAMIC PDO PREPARED STATEMENT 
$sql="SELECT *
FROM mytable
WHERE (object_id, object_type) IN (";
$i=0;
foreach($data as $datum){
    if($i!=0){
        $sql.=",";
    }
    $i=1;
    $sql.="(?,?)";
}
$sql.=")";

$stmt=$connection->prepare($sql);

$execute_data=array();
foreach($data as $datum){
    array_push($execute_data,$datum['object_id']);
    array_push($execute_data,$datum['object_type']);
}
$stmt->execute($execute_data);