MYSQL - 如何构建此查询?

时间:2013-01-21 12:39:49

标签: mysql sql select aggregate-functions

我想获得一个仅列出成员名称的团体及其成员列表(仅一次):

TABLE_A:

| GROUP_ID |   NAME |
---------------------
|        1 |    Tom |
|        2 |  Frank |
|        3 | Shilla |
|        1 | Scully |
|        3 | Scully |
|        3 | Scully |
|        3 | Scully |
|        4 | Scully |
|        1 |    Jen |

表-B:

| ID | GROUP_NAME |
-------------------
|  1 |   Troopers |
|  2 |      Clubs |
|  3 |  Mavericks |
|  4 |   Tomatoes |

这是SQLFidlle
这是结果:

| GROUP_NAME |        GROUP_CONCAT(C.NAME) |
--------------------------------------------
|  Mavericks | Scully,Scully,Scully,Shilla |
|   Tomatoes |                      Scully |
|   Troopers |              Scully,Jen,Tom |

我想得到的是

| GROUP_NAME | GROUP_CONCAT(C.NAME) |
-------------------------------------
|  Mavericks | Scully,Shilla        |
|   Tomatoes | Scully               |
|   Troopers | Scully,Jen,Tom       |

我该如何更改查询?

3 个答案:

答案 0 :(得分:3)

只需添加DISTINCT

SELECT  b.GROUP_NAME, GROUP_CONCAT(DISTINCT c.Name)
FROM    
        (
            SELECT GROUP_ID
            FROM   table_a
            WHERE  name = 'Scully'
            GROUP BY table_a.GROUP_ID
        ) a 
        INNER JOIN table_b b
            ON a.GROUP_ID = b.ID
        INNER JOIN table_a c
            ON a.GROUP_ID = c.GROUP_ID
GROUP BY b.GROUP_NAME;

答案 1 :(得分:2)

只需将DISTINCT添加到GROUP_CONCAT即可。请参阅MySQL docs

... GROUP_CONCAT(DISTINCT C.NAME) ...

答案 2 :(得分:0)

尝试此查询

SELECT 
    * 
FROM table_b as b
LEFT JOIN (
    SELECT 
          GROUP_CONCAT(DISTINCT NAME) as Names,
          GROUP_ID
    FROM Table_a 
    GROUP BY GROUP_ID
) as a ON a.GROUP_ID = b.ID

SQL FIddle