使用JOIN修改多列查询的结果

时间:2014-10-08 21:49:15

标签: sql postgresql

我与postgresql 9.1合作。

我有两个链接表: 表事件:

 eventid |    name    
---------+------------
       1 | event1
       2 | deuxieme
       3 | troisieme3

和表格图像链接到这样的事件:

 id |          path          | alt  | eventid | 
----+------------------------+------+---------+
  1 | /something/to/img.jpg  | alt  |       1 |      
  2 | /something/to/img2.jpg | alt2 |       1 |      
  3 | /something/to/img3.jpg | alt3 |       2 |   

我想返回包含链接路径和alts的所有事件的列表。到目前为止,我使用了这个查询:

 SELECT events.eventId, events.name, string_agg(distinct images.path, ',') AS paths, string_agg(distinct images.alt, ',') AS alts
    FROM events
    LEFT JOIN images ON images.eventId = events.eventId
    GROUP BY events.eventId;

但是有一个问题,它会返回:

 eventid |    name    |                    paths                     |   alts   
---------+------------+----------------------------------------------+----------
       1 | event1     | /something/to/img2.jpg,/something/to/img.jpg | alt,alt2
       2 | deuxieme   | /something/to/img3.jpg                       | alt3
       3 | troisieme3 |                                              | 

正如您所看到的那样,路径和路径不是相同的顺序,目前无法知道哪些路径和路径对应于同一图像。所以我的问题是:有没有办法在结果中对它们进行分组,或者如果不可能,我怎样才能以相同的顺序呈现它?谢谢;)

2 个答案:

答案 0 :(得分:1)

SELECT events.eventId, events.name, 
       array_to_string(array_agg(images.path order by id), ',') AS paths, 
       array_to_string(array_agg(images.alt  order by id), ',') AS alts
    FROM events
    LEFT JOIN images ON images.eventId = events.eventId
    GROUP BY events.eventId, events.name;

答案 1 :(得分:1)

我想最简单的修改 - 如果你不希望结果在不同的行上 - 将只是逗号分隔值,url,alt,url,alt,...这将使DISTINCT在整体上工作URL / ALT一次配对。

SELECT events.eventId, events.name, 
string_agg(distinct images.path || ',' || images.alt, ',') AS images
FROM events
LEFT JOIN images ON images.eventId = events.eventId
GROUP BY events.eventId, events.name;

An SQLfiddle to test with