0

我希望做的是在查询中从表中创建一个字符串,以便我可以将该字符串放在我正在创建的另一个查询中。说,我有这张桌子:

index | position   | name
----------------------------------------
1     | member     | John Smith
2     | chair      | Mary Jones
3     | member     | Mary Jones
4     | contact    | Grace Adams
5     | director   | Grace Adams
6     | member     | Grace Adams
7     | treasurer  | Bill McDonnell
8     | vice chair | Bill McDonnell
9     | member     | Ishmael Rodriguez

我正在寻找如下结果:

name               | positions
----------------------------------------
John Smith         | member
Mary Jones         | chair,member
Grace Adams        | contact,director,member
Bill McDonnell     | treasurer,vice chair
Ishmael Rodriguez  | member

我希望我可以使用 CONCAT_WS() 的一些变体来获得我的结果,就像这样......

SELECT
a.NAME,
CONCAT_WS(
    ',',
    (
        SELECT
            position
        FROM
            TABLE
        WHERE
            NAME = a.NAME
    )
)AS positions FROM ---------------

显然,这不适合我。有任何想法吗?

4

2 回答 2

4

使用GROUP_CONCAT [文档]

SELECT name, GROUP_CONCAT(position) result
FROM tableName
GROUP BY name
ORDER BY `index`
于 2012-11-01T14:55:35.350 回答
1

GROUP_CONCAT像这样使用:

SELECT name, GROUP_CONCAT(position SEPARATOR ',')
FROM Table
GROUP BY name
于 2012-11-01T14:55:57.510 回答