多行到一行制作一个场阵列?

时间:2014-08-15 08:59:31

标签: mysql sql join group-by

可能有类似的答案,但我花了一个多小时搜索并尝试建立相似性。分组有很多,但没有一个可以做我需要的。

基本上我想要多行并将它们组合成一行,将具有不同值的唯一列合并到一个数组中。我相信这些照片会有所帮助:

当前的SQL是:

SELECT mu.`firstname`AS firstname,
mu.`lastname`AS lastname,
mu.`username`AS username,
tu.`tagid` AS tagID
FROM user mu
LEFT JOIN tag_usertags tu ON (tu.`userid`= mu.`id`)
WHERE mu.id=10

目前:

----------------------------------------------------
|firstname | lastname     | username     | tagId   |
|--------------------------------------------------|
|Manager . | User  ....   |   manager..  |    2    |
|Manager . | User ....    |   manager..  |   11    |
|Manager . | User    .... |   manager..  |   46    |
|Manager . | User    .....|   manager..  |   8     |
|Manager . | User  ....   |   manager..  |   31    |
|Manager . | User    .... |   manager..  |   13    |
|Manager . | User   ....  |   manager..  |   41    |

我想看到的内容:

--------------------------------------------------------------------
|firstname | lastname       | username     |       tagId           |
|------------------------------------------------------------------|
|Manager.  | User  ......   |   manager..  | 2,11,46,8,31,13,41    |

1 个答案:

答案 0 :(得分:3)

您可以使用GROUP_CONCAT

SELECT mu.`firstname`AS firstname,
  mu.`lastname`AS lastname,
  mu.`username`AS username,
  GROUP_CONCAT(tu.`tagid` SEPARATOR ',') AS tagID
FROM user mu
LEFT JOIN tag_usertags tu ON (tu.`userid`= mu.`id`)
WHERE mu.id=10
GROUP BY mu.`firstname`