如何合并三个表(MySQL)?

时间:2019-11-21 23:31:33

标签: php mysql laravel

我有三个桌子。

enter image description here

enter image description here

enter image description here

我想从上表中获得以下结果。

enter image description here

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

谢谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用此代码

$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);

这样的结果

enter image description here

如果提交的产品可以具有多个属性,则可以将此属性与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);

结果类似

enter image description here