tags:

views:

49

answers:

1

Hi Guys

I would like to know if it's possible to order by a comma-delimited set returned by a subquery?

I have the following:

SELECT navigation.id, documents.template_id
FROM navigation
INNER JOIN documents 
    ON navigation.document_id = documents.id
    AND FIND_IN_SET(navigation.id,(SELECT numeric_lineage 
                                     FROM navigation WHERE id = #id#))
ORDER BY ???

Now I'm not certain how I would go about ordering the results in the same order as the comma-delimited set in numeric_lineage. Is it possible? I would prefer not to have to do another subquery if possible.

Thanks

+2  A: 

You can use FIND_IN_SET in the ORDER BY clause:

ORDER BY FIND_IN_SET(navigation.id, (SELECT numeric_lineage 
                                       FROM navigation WHERE id = #id#))
OMG Ponies
Awesome, I had no idea this was possible! I'm just concerned about having 2 subqueries now. Would it be more beneficial (server load) doing a separate query for the numeric_lineage, replacing the 2 subqueries with the string, and using an IN instead of the first FIND_IN_SET? I have always been under the impression subqueries "were the devil"? ;-)
Bjorn
@Bjorn: If subqueries were so bad, the functionality would've been removed entirely. From a maintenance perspective, it sucks to have identical queries but MySQL doesn't support the WITH clause (not sure that it would support this anyway) so I don't see any way around the issue.
OMG Ponies
Great, thanks you for your help. Very much appreciated! :-)
Bjorn
Subqueries are bad, but CSV in database is much worse, normalize your schema!
Naktibalda
@Bjorn: I'd be more worried about your table structure. Comma-separated-strings are a huge schema-smell. You should usually be using a join table (eg. of `owner_navigation_id, child_navigation_id, order_number`) to structure lists, to gain the benefits of indexing and foreign keys.
bobince
Thanks guys, I am fully aware this is bad practice in that regard, but I do have the actual navigation structure setup correctly. This field is simply a reference to the level structure which I store to avoid having to loop through levels to find the 1st, 2nd, 3rd, etc parent. I am NOT using this field for anything other than ease of finding a parent X number of levels down the line.
Bjorn
There are better ways to store hierarchical data. See eg. nested sets.
bobince