【问题标题】:MySQL concat multiple row into one column using concat but without GROUPMySQL 使用 concat 但不使用 GROUP 将多行连接成一列
【发布时间】:2016-01-07 05:26:22
【问题描述】:

我有一个 Person 表,其中包含多个 Attributes,我想加入它们,所以我得到这样的结果:

First_Name | Last_Name | Attribute
======================================================
John       | Smith     | Cool, Tall, Brown Hair
Steve      | Bob       | Impatient, Short, Blonde Hair
Hector     | Hector    | Groovy, Funny, Black Hair

这些表格是:

Person {id, first_name, last_name}
Attribute {id, description}
Ref_Attribute {id, ref_person_id, ref_attribute_id}

我知道我可以使用 GROUP_CONCAT 并最终使用 GROUP BY person.id,但我不想使用 GROUP BY,因为我需要加入另一个表,我需要将它们分隔为不同的行。要加入的表是House。这意味着,如果一个人有多个房子,那么它将给出:

First_Name | Last_Name | Attribute                     | House
=======================================================================
John       | Smith     | Cool, Tall, Brown Hair        | Bourke St. Ave
Steve      | Bob       | Impatient, Short, Blonde Hair | Flinders St.
Hector     | Hector    | Groovy, Funny, Black Hair     | Crown Golf

有没有什么方法可以在没有 GROUP BY 的情况下加入并获得结果?

【问题讨论】:

    标签: mysql join


    【解决方案1】:

    如果问题是一个人可以拥有 1 栋或多栋房屋,并且您希望每栋房屋都在自己的行中,则可以按 Person.id 和 House.id 进行分组。

    SELECT p.first_name, p.last_name, GROUP_CONCAT(a.Description SEPARATOR ', ') as attributes, h.House
    FROM Person p
    LEFT JOIN Attributes a ON p.id = a.person_id
    INNER JOIN Houses h on p.id = h.person_id
    GROUP BY p.id, h.id
    

    这在功能上等同于上面 Rahul 的回答(如果您将上面的左连接更改为内部连接,但我认为您不想这样做)。您必须进行一些分析以查看哪个更快。

    【讨论】:

    • 嗨,马克,你的回答也很好。但我会和 Rahul 一起去,因为我是这样编码的。不过谢谢。
    【解决方案2】:

    你可以先得到分组,然后执行JOIN like

    SELECT p.first_name, p.last_name, xx.Attributes, h.Housees
    FROM Person p JOIN
    (
    SELECT id, GROUP_CONCAT(description) AS Attributes
    FROM Attribute 
    GROUP BY id ) xx ON p.id = xx.id
    JOIN House h on p.id = h.id;
    

    【讨论】:

      猜你喜欢
      • 2015-10-06
      • 1970-01-01
      • 2013-09-27
      • 2020-02-08
      • 2017-07-25
      • 1970-01-01
      • 2018-12-18
      • 2011-06-24
      • 2019-07-01
      相关资源
      最近更新 更多