两列上的GROUP_CONCAT

时间:2016-12-12 23:28:36

标签: mysql group-by aggregate-functions

我有那些表:

id | date | place

Party_Attendands

id | party_id | person_id | unknow_person_id

id | name | lastname

我想对一些数据进行非规范化并避免使用Party_Attendands。 基本上我想要一个像

这样的视图

Party& PartyPeople

id | date       | place | attendands_list
0  | 01/01/2016 | NY    | 1,2,3,4

以下查询会返回person_ids,但不会返回unknow_person_ids。撞人的人也是人:)。 如果不清楚,unknow_person_ids只是Persons的ID。因此,Party_Attendands的每一行都包含person_idunknow_person_id,但不是

所以attendands_list应该包含person_idsunknow_person_ids,目前只处理前者。

SELECT party.party_id, party.date, attendands.list
FROM party
LEFT OUTER JOIN
(
  SELECT party_id , GROUP_CONCAT( Party_Attendands.person_id
  ORDER BY person_id
  SEPARATOR  ',' ) AS list
  FROM Party_Attendands
  GROUP BY Party_Attendands.party_id 
) AS attendands 
ON party.party_id  = attendands.party_id 

1 个答案:

答案 0 :(得分:0)

TL; DR使用UNION

您可以将person_id和unknown_person_id值结合起来,就像这样。

                SELECT party_id, person_id
                  FROM Party_Attendands
                 UNION          
                SELECT party_id, unknown_person_id AS person_id
                  FROM Party_Attendands

然后您可以将这些项目分组,如下所示:

   SELECT party_id, 
          GROUP_CONCAT(DISTINCT person_id ORDER BY person_id) persons
     FROM (
                SELECT party_id, person_id
                  FROM Party_Attendands
                 UNION          
                SELECT party_id, unknown_person_id AS person_id
                  FROM Party_Attendands
          ) a
    GROUP BY party_id 

然后你可以把这个结果加到你的另一张桌子上。

SELECT p.id party_id, p.date, p.place, q.persons
  FROM Party p
  LEFT JOIN (
           SELECT party_id, 
                  GROUP_CONCAT(DISTINCT person_id ORDER BY person_id) persons
             FROM (
                        SELECT party_id, person_id
                          FROM Party_Attendands
                         UNION          
                        SELECT party_id, unknown_person_id
                          FROM Party_Attendands
                  ) a
            GROUP BY party_id
       ) q ON p.id = q.party_id

如果没有人出现,我想这不是派对。但是,LEFT JOIN仍允许您的结果集显示Party表中的行,即使您的其他表中没有相应的行也会显示。