mySQL:子查询到数组?

发布于 2024-10-05 09:01:31 字数 600 浏览 5 评论 0原文

我正在研究一个稍微复杂(至少对我来说)的 mySQL 查询,其中包含一个子查询,说实话,它不会很好。

SELECT `products`.`id`, `product`.`price`, 
  ( SELECT `value` FROM (`productValues`) 
    WHERE `productValues`.`product` = 'product.id'
  ) as values 
FROM (`products`) WHERE`product`.`active` = 1

当前结果如下所示:

Array
(
    [0] => Array
        (
            [id] => 1
            [active] => 1
            [price] => 1000
            [values] => 
        )
)

我想要的是值元素也成为一个数组,其中包含值表中匹配的所有元素(WHERE ProductValues.product = Product.id)。

我做错了什么?

I am working on a slight complex (at least for me) mySQL query containing a subquery and it isn't going to well to be honest.

SELECT `products`.`id`, `product`.`price`, 
  ( SELECT `value` FROM (`productValues`) 
    WHERE `productValues`.`product` = 'product.id'
  ) as values 
FROM (`products`) WHERE`product`.`active` = 1

The current result looks like this:

Array
(
    [0] => Array
        (
            [id] => 1
            [active] => 1
            [price] => 1000
            [values] => 
        )
)

What I want is the values element to also become an array with all elements in the Values table which matches (WHERE productValues.product = product.id).

What am I doing wrong?

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

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

发布评论

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

评论(5

好久不见√ 2024-10-12 09:01:31

我不确定你是否可以返回这样的子查询。解决方案是在子查询中使用 GROUP_CONCAT 将所有值连接到一个字符串。然后,在结果中,您可以使用 explode 将此字符串拆分为数组。

更新:子查询只能匹配 1 行
来源: http://dev.mysql.com/doc/refman /5.0/en/subquery-errors.html

I'm not sure if you can return subqueries like this. A solution would be to use GROUP_CONCAT in your subsquery to concatinate all values to a string. Then, in the result, you can split this string into an array using explode.

update : Subquery can only match 1 row
source : http://dev.mysql.com/doc/refman/5.0/en/subquery-errors.html

临走之时 2024-10-12 09:01:31
SELECT p.id, p.price, pv.`value`
FROM products p
  JOIN  productValues pv
  ON p.product_id=pv.product
WHERE p.active = 1
ORDER BY p.id;

给出一个表,其中每个 pv.value 一行(顺便说一句,不建议使用“value”等保留字)。按 p.id 对输出进行排序可确保特定产品的所有行都在一起。因此,在应用程序层中,循环遍历行,每次 p.id 更改时更改产品。

$old_id=NULL;
$datastructure=array();
while($arr=$result->fetch_assoc()){
  if($arr['id']!=$old_id){
    $datastructure[$arr['id']][price]=$arr['price'];
    $old_id=$arr['id'];
  }
  $datastructure[$arr['id']]['values'][]=$arr['value'];
}

我给出的结构可能比您要求的结构更灵活,因为它允许您通过数组键访问特定产品。

SELECT p.id, p.price, pv.`value`
FROM products p
  JOIN  productValues pv
  ON p.product_id=pv.product
WHERE p.active = 1
ORDER BY p.id;

gives a table with one row for each pv.value (BTW, using reserved words like 'value' is not recommended). Ordering the output by p.id ensures that all the rows for a particular product are together. So, in the application layer, loop through your rows, changing product each time the p.id changes.

$old_id=NULL;
$datastructure=array();
while($arr=$result->fetch_assoc()){
  if($arr['id']!=$old_id){
    $datastructure[$arr['id']][price]=$arr['price'];
    $old_id=$arr['id'];
  }
  $datastructure[$arr['id']]['values'][]=$arr['value'];
}

The structure I've given is perhaps more flexible than the one you asked for in that it allows you to access a particular product through the array key.

べ繥欢鉨o。 2024-10-12 09:01:31

我认为“值”属性始终是一个变量。想想纯 SQL,不管 PHP - 如果您在 sql 编辑器中运行类似的查询 - 您将获得作为一列的值属性。如果您要求检索多于一列,则会出现错误。
一般来说,SQL 查询始终是平坦的 - 一级。
我的建议 - 运行 2 个查询,并将它们放在 PHP 层中。

I think the 'values' attribute will always be one variable. Think pure SQL, regardless of PHP - had you run a query like that in your sql editor - you would get the values attribute as one column. Had you asked for more than one column to be retrieved, you would have gotten an error.
In general, SQL queries are always flat - one level.
My suggestion - run 2 queries, and put them together in the PHP layer.

小嗲 2024-10-12 09:01:31

MySQL只能返回二维结果集,无法返回更复杂的数据结构。您必须进行两个单独的查询并将结果合并到您的应用程序中。

PHP 中的示例:

<?php

//getting a list of products
$result = mysql_query("SELECT `products`.`id`, `product`.`price`
                        FROM (`products`)
                        WHERE`product`.`active` = 1");

$product_ids = array();
$products = array();
while($r = mysql_fetch_assoc($result))
{
    $products[$r['id']] = $r;
    $product_ids[] = $r['id'];
}

$comma_separated_ids = implode(",", $product_ids);

//getting a list of all product values for given products
$result = mysql_query("SELECT `value`, `product`
                        FROM (`productValues`)
                        WHERE `productValues`.`product` IN ('$comma_separated_ids')");

//joining them together
while($r = mysql_fetch_assoc($result))
{
    if (!isset($products[$r['product']]['values']))
        $products[$r['product']]['values'];

    $products[$r['product']]['values'][] = $r['value'];
}

?>

基于 GolezTrol 的答案的更优雅的变体:

<?php
$result = mysql_query("SELECT `products`.`id`, GROUP_CONCAT(`productValues`.`value`) AS `values` 
                        FROM `products`, `productValues`
                        WHERE`product`.`active` = 1 AND `productValues`.`product` = `products`.`id`
                        GROUP BY `products`.`id`");

$products = array();
while($r = mysql_fetch_assoc($result))
{
    $products[$r['id']] = $r;
    $products[$r['id']]['values'] = explode(',', $products[$r['id']]['values']);
}
?>

祝你好运!

MySQL can only return a two dimensional result set, it can't return a more complex data structure. You will have to make two separated queries and join a result in your application.

Example in PHP:

<?php

//getting a list of products
$result = mysql_query("SELECT `products`.`id`, `product`.`price`
                        FROM (`products`)
                        WHERE`product`.`active` = 1");

$product_ids = array();
$products = array();
while($r = mysql_fetch_assoc($result))
{
    $products[$r['id']] = $r;
    $product_ids[] = $r['id'];
}

$comma_separated_ids = implode(",", $product_ids);

//getting a list of all product values for given products
$result = mysql_query("SELECT `value`, `product`
                        FROM (`productValues`)
                        WHERE `productValues`.`product` IN ('$comma_separated_ids')");

//joining them together
while($r = mysql_fetch_assoc($result))
{
    if (!isset($products[$r['product']]['values']))
        $products[$r['product']]['values'];

    $products[$r['product']]['values'][] = $r['value'];
}

?>

A bit more elegant variant based on GolezTrol's answer:

<?php
$result = mysql_query("SELECT `products`.`id`, GROUP_CONCAT(`productValues`.`value`) AS `values` 
                        FROM `products`, `productValues`
                        WHERE`product`.`active` = 1 AND `productValues`.`product` = `products`.`id`
                        GROUP BY `products`.`id`");

$products = array();
while($r = mysql_fetch_assoc($result))
{
    $products[$r['id']] = $r;
    $products[$r['id']]['values'] = explode(',', $products[$r['id']]['values']);
}
?>

Good luck!

谜兔 2024-10-12 09:01:31

当我搜索“mysql 5.7 subquery into array”时,这是最重要的结果,所以即使这个问题很老,它也可以帮助其他人提到,从 MySQL 5.7.22 开始,一个可能的解决方案是使用聚合函数 JSON_ARRAYAGG(),不过使用的是 JOIN 而不是子查询。

更改 Silver Light 给出的示例:

SELECT `products`.`id`, JSON_ARRAYAGG(`productValues`.`value`) AS `values` 
FROM `products`, `productValues`
WHERE`product`.`active` = 1 AND `productValues`.`product` = `products`.`id`
GROUP BY `products`.`id`"

https ://dev.mysql.com/doc/refman/5.7/en/aggregate-functions.html#function_json-arrayagg

This came up as the top result when i searched for "mysql 5.7 subquery into array", so even though the question is old it could help others to mention that since MySQL 5.7.22 a possible solution is to use the aggretate function JSON_ARRAYAGG(), though with JOIN rather than a subquery.

Alteration of the example given by Silver Light:

SELECT `products`.`id`, JSON_ARRAYAGG(`productValues`.`value`) AS `values` 
FROM `products`, `productValues`
WHERE`product`.`active` = 1 AND `productValues`.`product` = `products`.`id`
GROUP BY `products`.`id`"

https://dev.mysql.com/doc/refman/5.7/en/aggregate-functions.html#function_json-arrayagg

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