如何对多个查询的结果进行交替排序?

How to sort the result of multiple queries alternatively?

我有一个由三个 select 子句组成的查询,如下所示:

select id, colors from table1
    union all
select id, numbers from table2 
    union all
select id, names from table3

这里还有表格结构:

// table1               // table2              //table3
+----+--------+        +----+---------+        +----+-------+
| id | colors |        | id | numbers |        | id | names |
+----+--------+        +----+---------+        +----+-------+
| 1  | red    |        | 1  | ten     |        | 1  | jack  |
| 2  | green  |        | 2  | two     |        | 2  | peter |
| 3  | blue   |        | 3  | one     |        +----+-------+
| 4  | yellow |        | 4  | three   |
+----+--------+        | 5  | six     |
                       | 6  | five    |
                       +----+---------+

现在我想要这样的结果顺序:

+----+--------+
| id | colors |
+----+--------+
| 1  | red    |
| 2  | ten    |
| 3  | jack   |
| 4  | green  |
| 5  | two    |
| 6  | peter  |
| 7  | blue   |
| 8  | one    |
| 9  | yellow |
| 10 | three  |
| 11 | six    |
| 12 | five   |
+----+--------+

我该如何实施? (需要注意的是,order by 1,2,3对我不起作用)

这就是你如何做到这一点

select @rn:=@rn+1 as id,colors from (
  (select @rn1:= @rn1+1 as rn,colors from table1,(select @rn1:=0)x order by id )
   union all 
  (select @rn2:= @rn2+1 as rn,numbers as colors from table2,(select @rn2:=0.5)x order by id)
   union all 
  (select @rn3:= @rn3+1 as rn,names as colors from table3,(select @rn3:=0.6)x order by id )
)x,(select @rn:=0)y order by rn ;

想法是为每个 table 项分配一个 rn 值,并且需要确保这些值始终按升序排列

因此,如果您 运行 每个 table 的查询,您将有

mysql> select @rn1:= @rn1+1 as rn,colors from table1,(select @rn1:=0)x order by id;
+------+--------+
| rn   | colors |
+------+--------+
|    1 | red    |
|    2 | green  |
|    3 | blue   |
|    4 | yellow |
+------+--------+
4 rows in set (0.00 sec)

mysql> select @rn2:= @rn2+1 as rn,numbers as colors from table2,(select @rn2:=0.5)x order by id;
+------+--------+
| rn   | colors |
+------+--------+
|  1.5 | ten    |
|  2.5 | two    |
|  3.5 | one    |
|  4.5 | three  |
|  5.5 | six    |
|  6.5 | five   |
+------+--------+
6 rows in set (0.00 sec)

mysql> select @rn3:= @rn3+1 as rn,names as colors from table3,(select @rn3:=0.6)x order by id;
+------+--------+
| rn   | colors |
+------+--------+
|  1.6 | jack   |
|  2.6 | peter  |
+------+--------+
2 rows in set (0.00 sec)

在这里你可以看到 table1 rn 值是 1,2,3,.... table2 值为 1.5,2.5,3.5,.... table3 值为 1.6,2.6,....

所以最后当你用所有 rn 排序结果时它会是

1,1.5,1.6,2,2.5,2.6,....