Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand correctly, then there should be a <strong>much simpler</strong> solution.</p> <h3>Test setup</h3> <p>According to your description - you could have done that for us:</p> <pre><code>CREATE TABLE table1 ( entry_id int4 PRIMARY KEY , entry_date date ); CREATE TABLE table2 ( entry_id int4 REFERENCES table1 (entry_id) , entry_subject text , PRIMARY KEY (entry_id, entry_subject) ); INSERT INTO table1 VALUES (1, '2011-09-01'), (2, '2011-09-02'),(3, '2011-09-03'); INSERT INTO table2 VALUES (1, 'foo1'), (2, 'foo2'), (2, 'bar2') , (3, 'foo3'), (3, 'baz3'), (3, 'bar3'); </code></pre> <h3>Answer</h3> <p><code>string_agg()</code> requires Postgres 9.0+</p> <pre><code>SELECT t1.entry_id, t1.entry_date , string_agg(t2.entry_subject, ', ') AS entry_subjects FROM table1 t1 JOIN table2 t2 USING (entry_id) GROUP BY 1,2 ORDER BY 1; entry_id | entry_date | entry_subjects ----------+------------+------------------ 1 | 2011-09-01 | foo1 2 | 2011-09-02 | bar2, foo2 3 | 2011-09-03 | baz3, bar3, foo3 </code></pre> <p>Or, if you want the entry_subjects <strong>sorted</strong>:</p> <pre><code>SELECT DISTINCT ON (1) t1.entry_id , t1.entry_date , string_agg(t2.entry_subject, ', ') OVER ( PARTITION BY t1.entry_id ORDER BY t2.entry_subject RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS entry_subjects FROM table1 t1 JOIN table2 t2 USING (entry_id) ORDER BY 1; entry_id | entry_date | entry_subjects ----------+------------+------------------ 1 | 2011-09-01 | foo1 2 | 2011-09-02 | bar2, foo2 3 | 2011-09-03 | bar3, baz3, foo3 </code></pre> <p>You could do the same with a subselect on <code>table2</code> to first <code>ORDER BY entry_subject</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload