在SQL列中串联选择

时间:2018-09-21 10:07:05

标签: mysql sql select

我有3个处于n-m关系的表。表A,表B和表A_has_B。

SELECT A.ID_Projectos, B.Nombre_Imagen 
FROM Table A_has_B 
INNER JOIN B on Table A_has_B.ID_Imagenes = B.ID_Imagenes 
INNER JOIN A on Table A_has_B.ID_Projectos = A.ID_Projectos

此sql select的输出是:

ID_Projectos | Nombre_Imagen
1            | Name_1.jpg
1            | Name_2.jpg
1            | Name_3.jpg

但是我需要这个输出...

ID_Projectos | Nombre_Imagen | Nombre_Imagen2 | Nombre_Imagen3
1            | Name_1.jpg    | Name_2.jpg     | Name_3.jpg

1 个答案:

答案 0 :(得分:0)

最简单的方法是将值连接到单个列中:

SELECT A.ID_Projectos, GROUP_CONCAT(B.Nombre_Imagen)
FROM Table A_has_B INNER JOIN
     B
     on Table A_has_B.ID_Imagenes = B.ID_Imagenes INNER JOIN
     A
     on Table A_has_B.ID_Projectos = A.ID_Projectos;

将其分为三列的最简单方法可能是使用字符串操作:

SELECT A.ID_Projectos,
       SUBSTRING_INDEX(GROUP_CONCAT(B.Nombre_Imagen), ',' 1) as imagen_1,
       (CASE WHEN COUNT(*) >= 2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(B.Nombre_Imagen), ',' 2), ',', -1) END) as imagen_2,
       (CASE WHEN COUNT(*) >= 3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(B.Nombre_Imagen), ',' 3), ',', -1) END) as imagen_3
FROM Table A_has_B INNER JOIN
     B
     on Table A_has_B.ID_Imagenes = B.ID_Imagenes INNER JOIN
     A
     on Table A_has_B.ID_Projectos = A.ID_Projectos
GROUP BY A.ID_Projectos;