sql格式化和提取项(json)

ia2d9nvy  于 2021-06-18  发布在  Mysql
关注(0)|答案(0)|浏览(330)

因此,基本上我应该总结和列出所有产品的基础上,他们的名字应该有所不同。如果我只选择了$[],这将正常工作。表中的项目,但如果我要用$[]选择所有项目。我会得到以下信息
行:

[{"brand_name": "Product 1", "brand_id": "4", "quantity": 1}, {"brand_name": "Product 2", "brand_id": "5", "quantity": 3}]

结果:

{
    "brand_id": "[\"4\", \"5\"]",
    "brand_name": "[\"Product 1\", \"Product 2\"]",
    "quantity": 0
}

预期结果:

{
    "brand_id": "4",
    "brand_name": "Product 1",
    "quantity": 1
}
{
    "brand_id": "5",
    "brand_name": "Product 2",
    "quantity": 3
}

有说服力的提问:

public function scopegetBasicMeans($query)
{        
    $query->where('type', 1)
        ->join('report_asset', 'report_asset.report_id', '=', 'reports.id')->select(
            DB::raw('JSON_UNQUOTE(JSON_EXTRACT(resources, "$[*].name")) as brand_name'), 
            DB::raw('JSON_UNQUOTE(JSON_EXTRACT(resources, "$[*].brand_id")) as brand_id'),
            DB::raw('SUM(JSON_EXTRACT(resources, "$[*].quantity")) as quantity')
        )->orderBy('quantity', 'DESC')
            ->groupBy(DB::raw('JSON_EXTRACT(resources, "$[*].name")'));
}

原始查询:

select JSON_UNQUOTE(JSON_EXTRACT(resources, "$[*].name")) as brand_name, JSON_UNQUOTE(JSON_EXTRACT(resources, "$[*].brand_id")) as brand_id, SUM(JSON_EXTRACT(resources, "$[*].quantity")) as quantity, `reports`.`created_at`, `commercialist_id`, `type` from `reports` inner join `report_asset` on `report_asset`.`report_id` = `reports`.`id` where `reports`.`object_id` = ? and `reports`.`object_id` is not null and `type` = ? and `reports`.`deleted_at` is null group by JSON_EXTRACT(resources, "$[*].name") order by `quantity` desc

基本上,我应该用特定的名称和质量的所有项目分组,他们的名字,这将得到唯一的结果我。如果我只从表中选择第一项(例如:$[0].name[0]),而不是在多个表中,这将起作用。有什么建议吗?
结构

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题