SQL将多个值放入一个以逗号分隔的列中

时间:2018-05-18 09:55:00

标签: mysql sql

需要一些关于此SQL查询的帮助。节点是产品表,每个产品在表field_data_field_images上有n个图像。我需要将所有这些图像文件名选择为一个以逗号分隔的列(例如" image1.jpg,image2.jpg"依此类推)。首先,我需要从field_data_field_images获取所有图像ID,然后从file_managed获取文件名。

SELECT node.*,
file_managed.filename,
field_data_field_product_code.field_product_code_value,
FROM node

LEFT JOIN field_data_field_images ON node.nid = field_data_field_images.entity_id
LEFT JOIN file_managed ON field_data_field_images.field_images_fid = file_managed.fid

WHERE node.language = 'lt' AND node.type = 'products'
GROUP BY nid

2 个答案:

答案 0 :(得分:1)

您可以使用group_concat()。以下查询还引入了表别名,因此查询更易于编写和阅读:

SELECT n.*,
       GROUP_CONCAT(fm.filename) as filenames
FROM node n LEFT JOIN
     field_data_field_images dfi
     ON n.nid = dfi.entity_id LEFT JOIN
     file_managed fm
     ON dfi.field_images_fid = fm.fid
WHERE n.language = 'lt' AND n.type = 'products'
GROUP BY n.nid

答案 1 :(得分:1)

如果MS-SQL遵循以下代码:

 DECLARE @TableVar TABLE
 (
  nid INT ,
  images NVARCHAR(400)
 );
 INSERT INTO @TableVar
    ( nid ,
      images
    )
    SELECT nid,images

FROM node

LEFT JOIN field_data_field_images 
ON node.nid =     field_data_field_images.entity_id
LEFT JOIN file_managed 
ON field_data_field_images.field_images_fid =   file_managed.fid

WHERE node.language = 'lt' AND node.type = 'products'
GROUP BY nid

SELECT DISTINCT
    nid ,
    STUFF(( SELECT  ',' + images
            FROM    @TableVar AS T
            WHERE   T.nid = T2.nid
          FOR
            XML PATH('')
          ), 1, 1, '') AS images
 FROM   @TableVar T2
 GROUP BY nid ,
    images