0

我想做一个SELECTtable A

table_a:

╔══════════╦════════╗
║ GROUP_ID ║  NAME  ║
╠══════════╬════════╣
║        1 ║ Tom    ║
║        2 ║ Frank  ║
║        3 ║ Shilla ║
║        1 ║ Scully ║
║        1 ║ Jen    ║
╚══════════╩════════╝


table_b:

╔════╦════════════╗
║ ID ║ GROUP_NAME ║
╠════╬════════════╣
║  1 ║ Troopers   ║
║  2 ║ Clubs      ║
║  3 ║ Mavericks  ║
╚════╩════════════╝

现在,我想显示给定成员名称的组:

SELECT GROUP_NAME,GROUP_CONCAT(table_a.NAME) MEMBERS     
FROM table_a     
JOIN  table_b ON table_a.GROUP_ID = table_b.ID   
WHERE
table_a.NAME = 'Scully'

我想得到这个:

╔════════════╦════════════════╗
║ GROUP_NAME ║    MEMBERS     ║
╠════════════╬════════════════╣
║ Troopers   ║ Tom,Scully,Jen ║
╚════════════╩════════════════╝

为什么这个查询不起作用?

4

3 回答 3

3
SELECT  b.GROUP_NAME, GROUP_CONCAT(c.Name) Members
FROM    
        (
            SELECT GROUP_ID
            FROM   table_a
            WHERE  name = 'Scully'
        ) 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

为了获得更好的性能,为 . 添加一个UNIQUE约束table_b.GROUP_Name

结果

╔════════════╦════════════════╗
║ GROUP_NAME ║    MEMBERS     ║
╠════════════╬════════════════╣
║ Troopers   ║ Tom,Scully,Jen ║
╚════════════╩════════════════╝
于 2013-01-21T01:05:04.990 回答
1

我认为你的 WHERE 条件太受限制了。

WHERE table_b.GROUP_NAME = 'Troopers'

如果你只有一个成员的名字,那么你需要使用另一个加入来获取组 ID:

试试这个:

SELECT table_b.GROUP_NAME, GROUP_CONCAT(table_a.NAME) MEMBERS     
FROM table_a     
JOIN  table_b ON table_a.GROUP_ID = table_b.ID   
JOIN  table_b `temp` ON table_a.GROUP_ID = temp.ID   
WHERE temp.NAME = 'Scully'
于 2013-01-21T00:57:07.503 回答
1
SELECT
    `group_name`,
    GROUP_CONCAT(a.`name`) AS 'members'
FROM `table_a` a
INNER JOIN `table_b` b
ON a.`group_id` = b.`id`
AND a.`group_id` = (
    SELECT `group_id` FROM `table_a` WHERE `name`='Scully'
)
GROUP BY NULL
于 2013-01-21T01:06:32.413 回答