合并来自两个具有不同列号的不同表的结果,按相同的键对它们进行排序


Merge results from two different tables with different column number, ORDER them by same key

我有两个表:

Table A: ID Cars Planes Num
          1    3      5   2
          2    8      44  1
          3    7      23  6
          4    6      2   7
Table B: ID Horses Dogs Cats Elefants Num
          1    3      5   2      3     3  
          2    8      44  1     22     4
          3    7      23  4     14     8
          4    6      2   3     15     5

我需要做的是:我需要从两个表中获取所有结果,并按"Num"列对它们进行排序,其中"数字"对于两行的每个结果实际上是唯一的。

甚至有可能"合并"这两个表并按"num"对它们进行排序,或者我应该分别对每个表进行排序并始终进行两个循环检查以在表之间跳转下一个 num?

谢谢

你可以像这样将它们与 UNION 合并。

试试这个:

select num from(
    select num from table1
    union all
    select num from table2
    )t
order by num asc

在这里演示

编辑:

select id ,Cars,Planes, Horses,Dogs,Cats,Elefants,num from(
    select id ,Cars,Planes,'No horses' Horses,'No dogs' Dogs,'No cats' Cats,'No elefants' Elefants,num from table1
union all
select id,'No cars' Cars,'No planes' Planes,Horses,dogs,Cats,Elefants, num from table2
 )t
 order by num asc;

与其他列一起删除

SELECT NUM FROM TABLEA
UNION ALL
SELECT NUM FROM TABLEB
ORDER BY 1