1

我想获得一个仅给出成员名称的组及其成员列表(仅显示一次):

表_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       |

我应该如何更改查询?

4

3 回答 3

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;
于 2013-01-21T12:41:32.717 回答
2

只需将 DISTINCT 添加到您的 GROUP_CONCAT。查看MySQL 文档

... GROUP_CONCAT(DISTINCT C.NAME) ...
于 2013-01-21T12:41:44.277 回答
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 小提琴

于 2013-01-21T12:43:23.200 回答