+ 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.
1 ответ
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