Skip to content
Advertisement

One-to-Many SQL SELECT concatenated into single row

I’m using Postgres and I have the following schemes.

Orders

Comments

So, in this case, an order can have many comments.

I need to iterate over the orders and get something like this:

I tried to use LEFT JOIN but it didn’t work

it returns this:

Advertisement

Answer

You are almost there – you just need aggregation:

I would strongly recommend against having a table (and/or a column) called order: because it conflicts with a language keyword. I would also recommend avoiding quoted identifiers as much as possible – they make the queries longer to write, for no benefit.

Note that you can also use a correlated subquery:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement