tags:

views:

72

answers:

1

Hi folks, i would like to get from a single table, all rows, but order them in different ways. For example i write

(SELECT * FROM table1
ORDER BY fieldA ASC LIMIT 3
)
UNION
(
SELECT * FROM table1
ORDER BY FieldB DESC
)

It works, excpet that the second order by (FIELDB DESC) is ignored... Somebody know Why ? Thank you

+6  A: 

The UNION operator performs an implied sort as part of the union operation (IIRC, on the key column(s)).

If you want other sorting in the result, you have to apply an ORDER BY to the unioned selection.

In your case, you need some way to distinguish between the first selection and the second, so that you can order the union properly. Something like (untested):

(SELECT table1.*, 0 AS TMP_ORDER FROM table1 ORDER BY fieldA ASC LIMIT 3)
UNION
(SELECT table1.*, 1 AS TMP_ORDER FROM table1)
ORDER BY TMP_ORDER ASC, 
CASE WHEN TMP_ORDER = 0 THEN fieldA ELSE 0 END ASC, 
CASE WHEN TMP_ORDER = 1 THEN fieldB ELSE 0 END DESC

The problem with this approach is that you'll have duplicates for the three rows selected as part of the first query in the UNION (since the columns don't totally match).

Are you sure you can't use two SELECT statments instead?

Ben M
@Mike, that question doesn't require distinct sorting based on unionorder. That's where the `CASE` statement comes in.
Ben M
The outer `select * ` isn't necessary, as well as the inner query `order by` s not doing anything in the 2nd query since there's no limit: `(select t1.*, 0 tmp_order from t1 order by fieldA asc limit 3) union (select t2.*,1 from t2) order by tmp_order, case ...`
Donnie
+1 @Mike - that answer only sorts by which subquery the data came from, no second level sort to ensure FieldA and FieldB are also sorted from their respective queries. The answer here includes the second level sort.
mdma
@Donnie, that's my SQL Server background showing. Also, I commented out the `order by` in the union's second query.
Ben M
@Ben - sql server doesn't require the outer select either ;) (I also didn't know this for a long time and wrote queries just like this)
Donnie
@Donnie, just tested - you're right - thanks for the tip!
Ben M
@Mike, radius's answer is identical to mine, except that this question requires more complex sorting of the unioned result. Not much more to it than that.
Ben M
@Ben M: I was hasty with my previous comments, please accept my apologies - I had thought that radius's answer also sorted each select individually. After some testing, I see the difference. Your solution is quite ingenious.
Mike
@Mike, no problem at all! Thanks for saying so.
Ben M