简体   繁体   中英

Select multiple records by one query

Please, give me advice, how to construct select query. I have table table with fields type and obj_id . I want to select all records in concordance with next array:

$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),
);

I want to select needed rows by one query, is it real? Smth like

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

But this query returns also records with type = 3 and obj_id = 14, and for example type = 1 and obj_id = 17. ps moderators, please fix my title, I dont know how to describe my question.

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

据我知道你不能用in了这一点,但你必须退回到这样的事情

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

If I understand correctly, you can use either UNIONs or ORs. Using 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

Remove the ALL from the UNION ALL if you need to remove duplicates.

Using ORs:

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)

The brackets are important - they indicate that all the things inside need to be satisfied.

I recommend using UNIONs - ORs are notorious for bad performance.

$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 ';
}

should form $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); 

如果条件数组变大,则可能需要创建索引临时表,在table (type, obj_id)上具有复合索引table (type, obj_id)然后执行INNER JOIN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM