【问题标题】:Summing mysql json objects with multiple indexes总结具有多个索引的mysql json对象
【发布时间】:2018-11-14 11:57:57
【问题描述】:

在从数据库中选择 json 数据时,我遇到了问题。 有没有办法按索引提取数据。

我需要这个,因为我想按 json 项目的名称求和和分组,如果我从数组中提取第一个项目,我可以做到这一点:

DB::raw('JSON_UNQUOTE(JSON_EXTRACT(resources, "$[0].name[0]")) as brand_name'), 
DB::raw('JSON_UNQUOTE(JSON_EXTRACT(resources, "$[0].brand_id[0]")) as brand_id'),
DB::raw('SUM(JSON_EXTRACT(resources, "$[0].quantity[0]")) as quantity')

然后我会按 $[0].name[0] 分组,我会得到独特的结果。

存储在sql中的数据:

[[{\"name\": \"Product 1\", \"brand_id\": \"2\", \"quantity\": 2}, 
{\"name\": \"Product 2\", \"brand_id\": \"3\", \"quantity\": 1}], 

[{\"name\": \"Product 3\", \"brand_id\": \"1\", \"quantity\": 2}, 
{\"name\": \"Product 1\", \"brand_id\": \"2\", \"quantity\": 5}], 

[{\"name\": \"Product 4\", \"brand_id\": \"4\", \"quantity\": 2}, 
{\"name\": \"Product 5\", \"brand_id\": \"5\", \"quantity\": 5}]]

如果您明白我的意思,我应该将所有同名产品的数量相加,并得到唯一的响应,而不是多个同名商品。 例如应该只有一个

产品 1,总数量为 7。

【问题讨论】:

    标签: php mysql json laravel


    【解决方案1】:

    假设您可以获取原始 JSON 字符串:

    $rawjson = '[[{\"name\":\"Product 1\",\"brand_id\": \"2\",\"quantity\": 2},{\"name\":\"Product 2\",\"brand_id\": \"3\",\"quantity\": 1}],[{\"name\": \"Product 3\", \"brand_id\": \"1\",\"quantity\": 2},{\"name\": \"Product 1\", \"brand_id\": \"2\", \"quantity\": 5}],[{\"name\": \"Product 4\", \"brand_id\": \"4\",\"quantity\": 2},{\"name\": \"Product 5\", \"brand_id\": \"5\",\"quantity\": 5}]]';
    
    $master = json_decode(stripslashes($rawjson), true);
    
    $p1Sum = 0;
    $p2Sum = 0;
    $p3Sum = 0;
    $p4Sum = 0;
    
    foreach ($master as $subitems) {
        foreach ($subitems as $item) {
          $itemName = $item['name'];
          switch($itemName){
          case 'Product 1':
            $p1Sum += $item['quantity'];
            break;
           case 'Product 2':
            $p2Sum += $item['quantity'];
            break;
           case 'Product 3':
             $p3Sum += $item['quantity'];
             break;
           case 'Product 4':
             $p4Sum += $item['quantity'];
             break;
          }
    
        }
    }
    
    echo 'Product 1: ' . $p1Sum . "\r\n";
    echo 'Product 2: ' . $p2Sum . "\r\n";
    echo 'Product 3: ' . $p3Sum . "\r\n";
    echo 'Product 4: ' . $p4Sum . "\r\n";
    

    会给你:

    Product 1: 7
    Product 2: 1
    Product 3: 2
    Product 4: 2
    

    【讨论】:

    • 是的,我知道如何使用 php 来做到这一点,但我的问题是,有没有办法通过查询来做到这一点?
    • 您可以使用 (JSON_CONTAINS)[dev.mysql.com/doc/refman/8.0/en/… 进行原始查询
    • 我应该再次运行它什么?函数我不太懂,数据是动态的。
    • 查看 JSON_CONTAINS here 的示例:
    猜你喜欢
    • 1970-01-01
    • 2017-06-03
    • 2013-03-12
    • 2018-02-28
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2021-02-11
    相关资源
    最近更新 更多