SQL 选择数组中的所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5508119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL select everything in an array
提问by bluedream
My homework has a problem for example there is a category array $cat=array('1','4','5','7'); now i need to select products from db based on the category that is
我的作业有问题例如有一个类别数组 $cat=array('1','4','5','7'); 现在我需要根据类别从数据库中选择产品
SELECT * FROM products WHERE catid='1'
SELECT * FROM products WHERE catid='4'
SELECT * FROM products WHERE catid='5'
SELECT * FROM products WHERE catid='7'
Is it possible to do this in a single query? as the final results of the four queries will be combined.
是否可以在单个查询中执行此操作?因为四个查询的最终结果将被合并。
回答by Senthil
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
回答by ustmaestro
// 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);
Update: (a short version and update missing comma)
更新:(简短版本和更新缺少逗号)
$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';
回答by Noor
$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;
It's more generic and will fit for any array!!
它更通用,适合任何数组!!