Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge Subquery results column into a single column then use in ORDER BY

I would like to execute some query like this:

SELECT 
    folders.*, 
    (SELECT 
        files.filename 
     FROM 
        files 
     WHERE 
        files.folder_id = folders.id 
    ) 
    as files 
FROM 
        folders 
ORDER BY 
    files[column name of filename]

The sub-query may give more than 1 result, so I would like to join the results into a single column filename.

I am using Postgres. I added Rails as a tag because you might suggest some Rails magic that can handle this.

like image 458
RodM Avatar asked Feb 18 '13 10:02

RodM


People also ask

Can you use a subquery in an order by?

An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.

Can we use subquery in Merge statement?

So the answer is no.

Is subquery executed for every row?

Each subquery is executed once for every row of the outer query. A correlated subquery is evaluated once for each row processed by the parent statement.


1 Answers

This will create a comma separated list of all files in the folder:

select folders.*,
       (SELECT string_agg(files.filename, ',')
        FROM files 
        WHERE files.folder_id = folders.id) as files
from folders

If you need the filenames to be sorted in the comma separated list, you can use an order by in newer Postgres versions:

select folders.*,
       (SELECT string_agg(files.filename, ',' order by files.filename)
        FROM files 
        WHERE files.folder_id = folders.id) as files
from folders

I'm not sure I understand the "and use it in ORDER BY" requirement though. If the column contains several files, how do you expect a proper order of the total result? You will need to show us some sample output (based on some sample data).

like image 75
a_horse_with_no_name Avatar answered Oct 05 '22 01:10

a_horse_with_no_name