MySQL使用concat将多行连接成一列,但没有GROUP

时间:2015-10-09 09:58:57

标签: mysql join

我有多个属性表,我想加入他们,所以我得到这样的结果:

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的结果吗?

2 个答案:

答案 0 :(得分:1)

您可以先进行分组,然后执行JOIN,如

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;

答案 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上面的回答(如果你将上面的左连接更改为内部,但我认为你不想这样做)。你必须做一些分析才能看出哪个更快。

相关问题