I'd like to do a SELECT
on table A
which has:
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 ║
╚════╩════════════╝
Now, I'd like to display the group given a name of the member:
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'
I'd like to get this:
╔════════════╦════════════════╗
║ GROUP_NAME ║ MEMBERS ║
╠════════════╬════════════════╣
║ Troopers ║ Tom,Scully,Jen ║
╚════════════╩════════════════╝
Why does this query not work?
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
for better performance, add a UNIQUE
constraint for table_b.GROUP_Name
.
RESULT
╔════════════╦════════════════╗
║ GROUP_NAME ║ MEMBERS ║
╠════════════╬════════════════╣
║ Troopers ║ Tom,Scully,Jen ║
╚════════════╩════════════════╝
I think your WHERE condition is too restricted.
WHERE table_b.GROUP_NAME = 'Troopers'
If you only have the name of a member then you'll need to get the group id using another join:
Try with this:
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'
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.