SQL 选择数组中的所有内容

发布于 2024-10-28 01:54:29 字数 296 浏览 1 评论 0原文

我的作业有一个问题,例如有一个类别数组 $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'

是否可以在单个查询中执行此操作?因为四个查询的最终结果将被合并。

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

够钟 2024-11-04 01:54:29
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
指尖上得阳光 2024-11-04 01:54:29
// 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);

更新:(简短版本并更新缺少的逗号)

$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';
// 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) . ')';
青朷 2024-11-04 01:54:29
$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;

它更通用,适合任何阵列!

$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!!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文