I'm using php and need to do a bunch of select statements on the same table and column and get the rows that match those values.
I have all the values I'm searching on in an array and right now I'm just looping and doing a select statement on each one separately. How could I put t开发者_如何学编程his all into one select statement and ditch the loop?
Right now it's like this:
for (yaddah yaddah yahhah){
SELECT * FROM scan WHERE order=var[$i];
}
You could use IN
to specify a list of values :
select *
from scan
whenre order IN (1, 5, 46, 78)
And you can get such a list using the implode
function :
$array = array(1, 5, 46, 78);
$list_str = implode(', ', $array);
// $list_str is now "1, 5, 46, 78"
$query = "select *
from scan
where order IN ($list_str)
";
After, in your PHP script, it's only a matter of fetching several lines instead of only one.
Use IN
and implode
as follows:
$sql = "SELECT * FROM `scan` WHERE `order` IN (" . implode(',', $array) . ")";
Check out SQL's In Operator
精彩评论