This question already has answers here:
How can I return pivot table output in MySQL?
                                
                                    (8个答案)
                                
                        
                                2年前关闭。
            
                    
自2天以来,我一直在寻找解决方案...


我有两个表:

-组成部分-栏目:
id |名称|描述

-components_ingredients-列:
component_id | Ingredient_id

=>一种成分可以有多种成分

所以当我用语句加入表格时:

选择*从组件c
  内联接components_ingredients ci ON c.id = ci.component_id

表ci中的每种成分我都返回一行。但是我只想返回匹配成分的一行作为其他列,例如:

c.id | c.name | c。说明| ci.ingredient1 | ci.ingredient2 | ci.ingredient3 ...

这可能吗?何时?

谢谢

最佳答案

您可以尝试使用MySQL的GROUP_CONCAT()函数创建每个给定组件的成分的CSV列表。

SELECT c.id, c.name, c.description, ci.ingredients
FROM components c
INNER JOIN
(
    SELECT component_id, GROUP_CONCAT(ingredient_id) AS ingredients
    FROM components_ingredients
    GROUP BY component_id
) ci
    ON c.id = ci.component_id


请注意,正如@Gordon所指出的,您可以在没有我使用的子查询的情况下进行操作,但是通常您可能需要它。即使根据ANSI标准,戈登查询工作的原因是id表中的给定components应该唯一地确定namedescription。因此,在使用GROUP BY时可以包括那些列,因为没有歧义。

关于mysql - SQL连接映射表并获取列而不是行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43169721/

10-12 12:28
查看更多