SELECT a.ID, a.name, GROUP_CONCAT(CASE WHEN relation = 'friend' THEN b.name ELSE NULL END) friend, GROUP_CONCAT(CASE WHEN relation = 'brother' THEN b.name ELSE NULL END) brother, GROUP_CONCAT(CASE WHEN relation = 'parent' THEN b.name ELSE NULL END) parent FROM table_a a INNER JOIN table_b b ON a.id = b.id GROUP BY a.ID, a.name
in the future, if you have a different relationship than friend, brother, and parent , and you do not want to change the request, you can use the prepared statement
SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'GROUP_CONCAT(CASE WHEN relation = ''', relation, ''' then b.name ELSE NULL end) AS ', relation ) ) INTO @sql FROM table_b; SET @sql = CONCAT('SELECT a.ID, a.name, ', @sql, ' FROM table_a a INNER JOIN table_b b ON a.id = b.id GROUP BY a.ID, a.name'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
source share