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

标签 mysql sql-order-by union-all

我有一个由三个 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 ;

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

因此,如果您对每个表运行查询,您将拥有

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,....

关于mysql - 如何对多个查询的结果进行交替排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33166093/

相关文章:

mysql - 从多个几乎相同的表中选择具有最大日期的行

php - PDO - 按价格升序或降序排列

php - CSV 文件生成错误

php - 转换日期时区时出现问题

PHP 查询不返回带有 varchar 的行

php - 如何使用带有 ORDER BY 子句的查询结果?

mysql - SQL 按结果计数排序

mysql - union 正在合并结果

sql - 联合还是联合所有人,这是个问题

MySQL 连接返回 Null