sql >> Base de Datos >  >> RDS >> Mysql

Combine varias filas secundarias en una fila MYSQL sin codificación fija o valores mínimos/máximos

Puede usar la siguiente consulta-

SELECT a.PK , a.Name, a.Email, 
SUBSTRING_INDEX(GROUP_CONCAT(i.Image_Name),',',1) AS Image_name_1, 
IF((LENGTH(GROUP_CONCAT(i.Image_Name)) - LENGTH(GROUP_CONCAT(i.Image_Name SEPARATOR ''))) < 1,'',SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(i.Image_Name),',',2),',',-1)) AS Image_name_2, 
IF((LENGTH(GROUP_CONCAT(i.Image_Name)) - LENGTH(GROUP_CONCAT(i.Image_Name SEPARATOR ''))) < 2,'',SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(i.Image_Name),',',3),',',-1),',',-1)) AS Image_name_3, 
IF((LENGTH(GROUP_CONCAT(i.Image_Name)) - LENGTH(GROUP_CONCAT(i.Image_Name SEPARATOR ''))) < 3,'',SUBSTRING_INDEX(GROUP_CONCAT(i.Image_Name),',',-1)) AS Image_name_4 
 FROM `advertiser` a
    LEFT JOIN category  c ON a.PK = c. FK 
    LEFT JOIN images I ON a.PK = i.FK
    WHERE c.FK = 1
    GROUP BY a.PK, a.Name,a.Email;