mysql查询以获取产品变体

ctrmrzij  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(352)

我正在尝试获取要在产品页面上显示的产品变量属性。我想要以下输出:
颜色:红色(尺寸:s,m),绿色(尺寸:s)
但我得到了:
颜色:红色,绿色尺寸:s,m
这是我到目前为止得到的一个简化版本:

PRODUCT TABLE
|    id     |
-------------
|     1     |
|     1     |
|     1     |
VARIANT TABLE
|    id     |fk_product_id|
---------------------------
|     1     |       1     |
|     2     |       1     |
|     3     |       1     |
ATTRIBUTE TABLE
|fk_variant_id| property |  value    |
--------------------------------------
|     1     |   color   |     red    |
|     1     |    size   |      S     |
|     2     |   color   |     green  |
|     2     |    size   |      S     |
|     3     |   color   |     red   |
|     3     |    size   |      M     |
$stmt=$db->prepare('SELECT
    attribute.property AS property,
    GROUP_CONCAT(DISTINCT attribute.value) AS value
FROM product
INNER JOIN variant
    ON product.id=variant.fk_product_id
LEFT JOIN attribute
    ON variant.id=attribute.fk_variant_id
WHERE product_id=:product_id
GROUP BY attribute.property');

$stmt->bindParam(':product_id',$product_id);
$stmt->execute();
$query=$stmt->fetchAll();
foreach($query as $row){
  echo $row['property'].' '.$row['value'].'<br>';
}

最后的游戏是这样的:

tct7dpnv

tct7dpnv1#

此查询应提供所需的结果。它有效地创建每个属性的表( color 以及 size )并将它们与产品和变体结合起来。

SELECT p.id AS product, c.value AS color, GROUP_CONCAT(s.value) AS sizes
FROM product p
JOIN variant v ON v.fk_product_id = p.id
LEFT JOIN attribute c ON c.fk_variant_id = v.id AND c.property = 'color'
LEFT JOIN attribute s ON s.fk_variant_id = v.id AND s.property = 'size'
GROUP BY product, color

输出

product     color   sizes
1           green   S
1           red     S,M

在dbfiddle上演示

相关问题