+ 1

How does sql UNION can combine the ORDER BY result?

I used sql1: Select * From my_table Where column_a='aa' Order By column_b desc Limit 2. And I used sql2: Select * From my_table_2 Where column_a='bb' Order By column_b desc Limit 2. Then I combined the result like this: Select * From my_table Where column_a='aa' Order By column_b desc Limit 2 Union Select * From my_table_2 Where column_a='bb' Order By column_b desc Limit 2 The result is like this column_a column_b aa 15 aa 10 bb 21 bb 11 , but I want the result like this column_a column_b bb 21 aa 15 bb 11 aa 10 Is there any way to order by after union. Thanks.

25th Jan 2018, 2:37 AM
gyoutou jyo
gyoutou jyo - avatar
1 Odpowiedź
0
SELECT * FROM ( SELECT TOP 2 * FROM my_table ORDER BY column_b DESC UNION ALL SELECT TOP 2 * FROM my_table_2 ORDER BY column_b DESC ) SubQuery ORDER BY column_b DESC Sorry if the syntax is a bit off. I'm most familiar with Microsoft SQL and don't have a DB readily available
25th Jan 2018, 3:56 AM
Jesse Bayliss
Jesse Bayliss - avatar