tags:

views:

43

answers:

3

I am looking to grab the first row (ordered by date descending) from a table, and then grab the rest of the rows (ordered by last_name ascending). I'm assuming I need to use a UNION statement for this, but I'm having trouble getting it to work.

Thanks in advance

+2  A: 

Why not run two queries? That seems like one obvious answer.

Not every task needs to be done in a single query. Do you write all your PHP code in one statement as well? ;-)

Bill Karwin
I know it would make more sense to do it separately (and I normally would), but without getting too much into the details, it would be much easier if there were a way to do it in 1 query.
Dylan
+2  A: 

Assuming using MySQL, you could use:

 (SELECT t.*
    FROM TABLE t
ORDER BY t.date DESC
   LIMIT 1)
UNION 
 (SELECT t.*
    FROM TABLE t
ORDER BY t.last_name)

You need to encapsulate the statements in brackets to apply the ORDER BY - otherwise, ORDER BY is applied to the resultset after the UNION.

OMG Ponies
@OMG Ponies: This will include that first row twice, once at the top and again lower, which the poster probably doesn't want.
Scott Stafford
@Scott Stafford: No, it won't because UNION removes duplicates. You'd be correct if it were `UNION ALL`
OMG Ponies
@OMG Ponies: Interesting... Learn something every day. Thanks.
Scott Stafford
+2  A: 
SELECT *
FROM yourtable
ORDER BY
    id = (SELECT id FROM yourtable ORDER BY date DESC LIMIT 1) DESC,
    last_name
Mark Byers
@Mark Byers: I like the "sort by calculated boolean flag" trick.
Scott Stafford
It appears to have worked. Thanks for your help!
Dylan