我的作业有问题,例如有一个类别数组$ cat = array('1','4','5','7');现在我需要根据
类别从db中选择产品SELECT * FROM products WHERE catid='1'
SELECT * FROM products WHERE catid='4'
SELECT * FROM products WHERE catid='5'
SELECT * FROM products WHERE catid='7'
是否可以在单个查询中执行此操作?因为四个查询的最终结果将合并。
答案 0 :(得分:49)
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
答案 1 :(得分:5)
// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');
// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';
// create sql
$SQL = 'SELECT * FROM products WHERE catid IN ' . $in;
// see what you get
var_dump($sql);
答案 2 :(得分:-1)
$SQL_Part="("
$i=0;
while ($i<length($cat)-1)
{
$SQL_Part+=$cat[i]+",";
}
$SQL_Part=$SQL_Part+$cat[$i+1]+")"
$SQL="SELECT * FROM products WHERE catid IN "+$SQL_Part;
它更通用,适合任何阵列!!