MySQL构建行组合

时间:2019-06-20 14:30:03

标签: mysql

我必须用其他2的组合来生成2列。我有一个包含产品属性的列,而另一个具有属性值的列,我需要做到这一点:

Attributes  Values
Color, Size Blue, L
Color, Size Blue, XL
Color, Size Red, L
Color, Size Red, XL

但是我有这个:

Attribute   Value
Color           Blue
Color           Red
Size            L
Size            XL

我看不到实现这一目标的方法,我也可以拥有颜色,尺寸,材质和其他类型的属性

我尝试使用group_concat,但在此示例中不起作用

SELECT 
p.products_id as 'product_id',
pd.products_name as 'name',
po.products_options_name as 'attributes',
trim(pov.products_options_values_name) as 'attribute_values'
-- GROUP_CONCAT(distinct(po.products_options_name)) as 'attributes',
-- GROUP_CONCAT(distinct(trim(pov.products_options_values_name))) as 'attribute_values'
FROM `products` AS p
INNER JOIN `products_description` AS pd ON p.`products_id` = pd.`products_id` 
INNER JOIN `products_attributes` AS pa ON p.`products_id` = pa.`products_id` 
INNER JOIN `products_options` AS po ON pa.`options_id` = po.`products_options_id` 
INNER JOIN `products_options_values` AS pov ON pa.`options_values_id` = pov.`products_options_values_id` 
WHERE p.products_id = '1476'
AND pd.language_id =3
group by trim(pov.products_options_values_name)
LIMIT 0 , 30```

2 个答案:

答案 0 :(得分:0)

假设您的表被格式化为两列,名称分别为'Attributes'和'Values',则可能会起作用。它将返回带有连接值的单列。

SELECT CONCAT(ca.Value,', ', cb.Value) AS 'Values' 
FROM (SELECT Value FROM table_name WHERE Attributes = 'Color') ca
CROSS JOIN (SELECT Value FROM table_name WHERE Attributes = 'Size') cb;

只需将table_name替换为表名。

答案 1 :(得分:-3)

请尝试以下

SELECT p.product_id || ',' || pd.products_name || ',' || po.products_options_name
FROM...

这将产生您需要的结果,但是您将它们分为两列 concat和group_concat可以工作,但是您不能在此处使用别名进行单独选择,也不能在以前的方法中使用