我想在一列中连接单元格

时间:2014-03-31 07:20:39

标签: mysql sql

我想根据id和他们所属的员工在一列中连接单元格。

我的表格是:

evenement:

id  |  title
1   |  hello
2   |  hi
3   |  bye

evenementontvanger:

id  |  idEvent  |  idWerknemer
1   |     1     |      2
2   |     1     |      20
3   |     2     |      3
4   |     2     |      18
5   |     3     |      2
6   |     3     |      20
7   |     3     |      26


Werknemer:
idWerknemer   |   Initialen
2             |      JD
3             |      HA
18            |      AD
20            |      RC
26            |      AJ

I would like to have an output like this for each different idEvent:
id  |  title   |   idEvent   |   idWerknemer   |   idWerknemer   |   Initialen  |   Initials
1   |  hello   |   1         |   2             |   2             |   JD         |   JD,RC
1   |  hello   |   1         |   20            |   20            |   RC         |   JD,RC

我尝试过使用CONCAT_GROUP但是会立即连接所有initialen。

  SELECT * 
FROM `evenement` LEFT JOIN `evenementontvanger` 
 ON `evenementontvanger`.`idEvent` = `evenement`.`id` 
 LEFT JOIN `Werknemer` ON `Werknemer`.`Initialen`= `evenementontvanger`.`idWerknemer`
 LEFT JOIN (SELECT `Initialen`,`idWerknemer`,
                  GROUP_CONCAT(`Initialen`) AS `Initials`
            FROM `Werknemer` ) a 
 ON a.`idWerknemer` = `evenementontvanger`.`idWerknemer`

 WHERE `idEvent`=`evenement`.`id` 
AND `evenementontvanger`.`idWerknemer` =a.`idWerknemer`

1 个答案:

答案 0 :(得分:1)

您可以使用共同相关的子查询,它将在逗号分隔列表中显示事件的所有相关项目,并在所需结果集中显示重复的事件列表

SELECT * 
,
(SELECT GROUP_CONCAT(ww.`Initialen`) FROM `Werknemer` ww
 JOIN evenementontvanger evv
 ON `ww`.`idWerknemer`= `evv`.`idWerknemer`
 WHERE `evv`.`idEvent`  = `e`.`id`
) INITIALENs
FROM `evenement`  e
LEFT JOIN `evenementontvanger`  ev
 ON `ev`.`idEvent` = `e`.`id` 
 LEFT JOIN `Werknemer` w 
ON `w`.`idWerknemer`= `ev`.`idWerknemer`

Fiddle

如果您需要为不同的活动展示,您可以这样做

SELECT * 
,
(SELECT GROUP_CONCAT(`w`.`Initialen`))
 INITIALENs
FROM `evenement`  e
LEFT JOIN `evenementontvanger`  ev
 ON `ev`.`idEvent` = `e`.`id` 
 LEFT JOIN `Werknemer` w 
ON `w`.`idWerknemer`= `ev`.`idWerknemer` GROUP BY e.id

Fiddle 2