简体   繁体   English

合并多个SQL查询结果

[英]Combine multiple SQL query results

I am working with PHP and I have made this code: ` 我正在使用PHP,并且已经编写了以下代码:

        $categories = array('casual','dinner', 'kids');
            $numberOfCategories = count($categories);

                for ($i=0; $i < $numberOfCategories; $i++) { 

                    $req = $pdo->query('
                    SELECT ProductID
                         , ProductCategoryID 
                      FROM products 
                     WHERE ProductCategoryID LIKE "%'.$categories[$i].'%" 
                     ');

                    while (${"relatedProduct" . $i} = $req->fetch()) {
                        var_dump(${"relatedProduct" . $i});
                    }
                }

` `

After running the code I got the following result: 运行代码后,我得到以下结果: 查询结果

If you look at it closely, you will notice that certain products repeat them self (which is normal). 如果仔细观察,您会发现某些产品会自我重复(这是正常现象)。

What I want to do now his to combine the result of each loop stored in the variable ${"relatedProduct" . $i} 我现在想做的就是合并存储在变量${"relatedProduct" . $i}的每个循环的结果${"relatedProduct" . $i} ${"relatedProduct" . $i} and filter that result(result after combining the result of each loop) to avoid repetition of products based on the column ProductID ${"relatedProduct" . $i}并过滤该结果(合并每个循环的结果后的结果),以避免基于ProductID列重复乘积

Kindly help me solve this problem. 请帮助我解决这个问题。

Avoid inclusion of strings directly into SQL (potential danger of SQL injection attacks). 避免将字符串直接包含到SQL中(SQL注入攻击的潜在危险)。 Use parameterized prepared statements instead. 请改用参数化的准备好的语句。

DISTINCT will give you unique rows (Prod.ID / Cat.ID combination). DISTINCT将为您提供唯一的行(产品ID /产品ID组合)。 You can combine the search needles with | 您可以将搜索针与|结合使用| and compare it as a regular expression by RLIKE . 并由RLIKE将其作为正则表达式进行比较。 The result is the sum of what you get with LIKE %needle% on each. 结果是每个LIKE %needle%得到的总和。

$req = $pdo->prepare('
  SELECT DISTINCT
    `ProductID`,
    `ProductCategoryID`
  FROM
    `products`
  WHERE
    `ProductCategoryID` RLIKE :pattern
  ');

$categories = array('casual','dinner', 'kids');
$cats = implode("|", $categories);

$req->bindParam(':pattern', $cats, PDO::PARAM_STR);
$req->execute();
$pdo->query(' SELECT GROUP_CONCAT(ProductCategoryID) as  ProductCategoryID
                      FROM products 
                     WHERE ProductCategoryID LIKE "%'.$categories[$i].'%" 
                     ');

using this U'll get a single row with all productCategoryIDs with matching conditions. 使用此方法,您将获得一个单行,其中包含所有具有匹配条件的productCategoryID。

Now you can use array_unique() function to get unique ProductCategoryID 现在,您可以使用array_unique()函数获取唯一的ProductCategoryID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM