What is the most efficient way to pull multiple rows from mysql by their ids?
I have a typical situation, where I need pull multiple rows from mysql by their ID's. I only know two methods how to do so, but I'm wondering if there is a better way to do this? and if there isn't, then which one of my own methods is most neatest/fastest/bette开发者_开发技巧r?
My 1st method: (~0.0003030)
$ids = array(3, 4, 6, 11);
foreach ($ids as $id) {
$task = $DB->query_first("SELECT * FROM tasks WHERE `id` = '$id'");
DoSomethingWithTheTask($task);
}
My 2nd method: (~0.0001040)
$ids = array(3, 4, 6, 11);
foreach ($ids as $id) {
$wheres[] = '`id` = \'' . $id . '\'';
}
$tasks = $DB->query("SELECT * FROM tasks WHERE " . implode(' OR ', $wheres));
while ($task = $DB->fetch_array($tasks)) {
DoSomethingWithTheTask($task);
}
The reason why I'm even considering the second method, is because it uses only 1x query.. However, I strongly believe that both of these methods are not neat and need to be optimized. As far as I know, you cannot make a query like this: WHERE id = '2, 3, 4'
.
Actually, you can. IN operator does that.
SELECT * FROM tasks WHERE `id` IN (2, 3, 4)
would do the trick. you can use both numeric or string values with IN operator
As Johan failed with example, here is a right way
$ids = array(3, 4, 6, 11);
$in = implode(",",$ids);
$sql = "SELECT * FROM tasks WHERE `id` IN ($in)");
for the frequent use I'd make a placeholder, to call the whole expression this way
$ids = array(3, 4, 6, 11);
$data = $db->getArr("SELECT * FROM tasks WHERE `id` IN (?a)",$ids);
to answer your questions from the comments, here is a code from my db class
function escapeString($value)
{
return "'".mysql_real_escape_string($value,$this->connect)."'";
}
function createIN($data)
{
if (!is_array($data))
{
throw new E_DB_MySQL_parser("Value for ?a type placeholder should be array.");
}
if (!$data)
{
throw new E_DB_MySQL_parser("Empty array for ?a type placeholder.");
}
$query = $comma = '';
foreach ($data as $key => $value)
{
$query .= $comma.$this->escapeString($value);
$comma = ",";
}
return $query;
}
getArr() method has no direct relation to this as it's responsible for only type of result.
精彩评论