Mysql
 sql >> Base de données >  >> RDS >> Mysql

Combinez plusieurs lignes enfants en une seule ligne MYSQL sans codage en dur ni valeurs min/max

Vous pouvez utiliser la requête ci-dessous-

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;