【问题标题】:How can I combine three tables(MySQL)?如何组合三个表(MySQL)?
【发布时间】:2019-11-22 08:52:13
【问题描述】:

我有三张桌子。

我想从上面的表格中得到以下结果。

我正在从事 Laravel 项目。因此,如果可以,请使用 Laravel 查询生成器。 我想添加按重量排序。

提前致谢。

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    只需使用 SQL 左连接

        select p.id, color.value as 'color',weight.value as 'weight' from Products p
    left join Values color on (p.id = color.product_id)
        inner join Fields fcolor on (color.field_id = fcolor.id and fcolor.name = "color")
    left join Values weight on (p.id = color.product_id)
        inner join Fields fweight on (weight.field_id = fweight.id and fweight.name = "weight")
    

    View The Result In SQL Command Tool

    【讨论】:

    • 谢谢,现在可以使用了。以及如何在结果表中按重量或颜色添加排序?提前致谢。
    • 您可以按weight.valuecolor.value排序。
    【解决方案2】:

    您可以使用此代码

    $fields = DB::table('fields')->pluck('name', 'id')->all();
    $query = DB::table('products')->selectRaw('id as product_id, name as product_name');
    foreach ($fields as $id => $value) {
        $raw = sprintf(
            '(select `value` from `values` where `values`.product_id = products.id  and `values`.field_id = %s LIMIT 1) as %s',
            $id,
            $value
        );
        $query->selectRaw($raw);
    }
    $result  = $query->get()->toArray();
    dd($result);
    

    这样的结果

    如果产品文件可以有多个属性,您可以将这个属性与GROUP_CONCAT一起使用

    $fields = DB::table('fields')->pluck('name', 'id')->all();
    $query = DB::table('products')->selectRaw('id as product_id, name as product_name');
    foreach ($fields as $id => $value) {
        $raw = sprintf(
            '(select GROUP_CONCAT(`value`) from `values` where `values`.product_id = products.id  and `values`.field_id = %s ) as %s',
            $id,
            $value
        );
        $query->selectRaw($raw);
    }
    $result  = $query->get()->toArray();
    dd($result);
    

    结果

    【讨论】:

    • 只更正你的表名products -> Products
    • 谢谢,但是如何添加按重量排序?
    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2013-05-16
    • 2021-11-21
    • 2012-09-12
    • 2021-08-26
    • 1970-01-01
    相关资源
    最近更新 更多