Preserving the order of records from a subquery when using the Merge Separate constructs

I want to make sure that the order of the result from the subquery is saved when using Union Different. Note that duplicate merging requires the use of "merge different".

For instance:

select columnA1, columnA2 from tableA order by [columnA3] asc
union distinct
select columnB1, columnB2 from tableB

When I run this, I expect that the records ordered from the subquery (select columnA1, columnA2from a tableAsort of [columnA3]asc), come first (as returned in order columnA3asc), and then out tableB.

I assume that I cannot add another dummy column because this would make the join great so as not to work. So this will not work:

select column1, column2 from 
 ( select column1, column2, 1 as ORD from tableA order by [columnA3] asc
 union distinct
 select column1, column2, 2 as ORD from tableB 
 ) order by ORD
+1
2

, MySQL "Union different". , , limit . , :

-1: Limit

         select columnA1, columnA2 from tableA order by [columnA3] asc Limit 100000000
         union distinct
         select columnB1, columnB2 from tableB

, , . , MySQL (http://dev.mysql.com/doc/refman/5.1/en/union.html):   " ORDER BY SELECT , , UNION . ORDER BY LIMIT, SELECT, UNION. ORDER BY LIMIT SELECT, , ."

, LIMIT 10000000000, , , .

-2: , .

        select column1, column2 from 
        ( select column1, column2 order by [columnA3] asc ) alias1
        union distinct
        ( select column1, column2 from tableB )

. (, http://dev.mysql.com/doc/refman/5.0/en/union.html), MySQL .

+4
select column1, column2 from 
 ( select column1, column2, 1 as ORD from tableA
 union distinct
 select tableB.column1, tableB.column2, 2 as ORD from tableB 
  LEFT JOIN tableA
      ON tableA.column1 = tableB.column1 AND tableA.column2 = tableB.column2
  WHERE tableA.column1 IS NULL
 ) order by ORD

, UNION ,

:

select column1, column2 from 
 ( select column1, column2, 1 as ORD from tableA
 union distinct
 select column1, column2, 2 as ORD from tableB 
 WHERE (column1, column2) NOT IN (SELECT column1, column2 from tableA)
 ) order by ORD
+1

Source: https://habr.com/ru/post/1539840/


All Articles