通过一个查询选择多个记录

时间:2010-05-31 15:57:35

标签: mysql

请给我建议,如何构建选择查询。我的表table包含字段typeobj_id。我想选择与下一个数组一致的所有记录:

$arr = array(
0 => array('type' => 1, 'obj_id' => 5),
1 => array('type' => 3, 'obj_id' => 15),
2 => array('type' => 4, 'obj_id' => 14),
3 => array('type' => 12, 'obj_id' => 17),
);

我想通过一个查询选择所需的行,是真的吗?像Smth一样

select * from `table` where type in (1,3,4,12) and obj_id in (5,15,14,17)

但是此查询还返回type = 3和obj_id = 14的记录,例如type = 1和obj_id = 17。 附:主持人,请修改我的标题,我不知道如何描述我的问题。

update: array $arr could contain more than 500 elems.

4 个答案:

答案 0 :(得分:3)

据我所知,你不能使用in,但你必须回到这样的事情

select * from `table` where type=1 and obj_id=5 or type=3 and obj_id=15

答案 1 :(得分:1)

如果我理解正确,您可以使用UNION或OR。使用UNIONs:

select * from `table` where type = 1 and obj_id = 5
UNION ALL
select * from `table` where type = 3 and obj_id = 15
UNION ALL
select * from `table` where type = 4 and obj_id = 14
UNION ALL
select * from `table` where type = 12 and obj_id = 17

如果您需要删除重复项,请从ALL移除UNION ALL

使用OR:

select * from `table` 
 where (type = 1 and obj_id = 5)
    OR (type = 3 and obj_id = 15)
    OR (type = 4 and obj_id = 14)
    OR (type = 12 and obj_id = 17)

括号重要 - 它们表示需要满足所有内容。

我建议使用UNIONs - OR因性能不佳而臭名昭着。

答案 2 :(得分:0)

$sql = 'select * from `table` where ';

foreach ($arr as $index => $conditions){
    $sql .= $or.' (';
    foreach($condicions as $key => $value){
       $sql .= $concat. "$key = $value";
       $concat = ' and ';
    }
    $sql .= ')';
    $or = ' or ';
}

应该形成$ sql as:

select * from table where 
  (type = 1 and obj_id = 5) or 
  (type = 3 and obj_id = 15) or 
  (type = 4 and obj_id = 14) or 
  (type = 12 and obj_id = 17); 

答案 3 :(得分:0)

如果条件数组变大,您可能想要创建一个索引临时表,在table (type, obj_id)上有一个复合索引并执行INNER JOIN