[英]Select multiple records by one query
請給我建議,如何構造選擇查詢。 我有表table
與字段type
和obj_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),
);
我想通過一個查詢選擇所需的行,這是真的嗎? 有點像
select * from `table` where type in (1,3,4,12) and obj_id in (5,15,14,17)
但是此查詢還會返回類型= 3和obj_id = 14的記錄,例如類型= 1和obj_id =17。ps主持人,請修正我的標題,我不知道如何描述我的問題。
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
如果我理解正確,則可以使用UNION或OR。 使用UNION:
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
如果需要刪除重復項,請從UNION ALL
刪除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)
括號很重要 -它們表示需要滿足內部的所有條件。
我建議使用UNION-OR因性能不佳而臭名昭著。
$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形成為:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.