我想在一个查询中使用UNION来选择两个表。然后我希望我的结果从两个表中混合(排序交替)。实际上我希望第一行结果来自table1
而第二行来自table2
,就像这样(关注输出顺序):
当我只使用时:
SELECT *
FROM table1
WHERE column1 = 'anything'
然后回显id,我的输出例如: 2,4,6
当我只使用时:
SELECT *
FROM table2
WHERE column1 = 'anything'
然后回显id,我的输出例如: 5,6,7
现在如何使用UNION和ORDER BY对输出进行排序: 2,5,4,6,6,7
答案 0 :(得分:0)
如果你想从联盟的结果中替换行,你需要给他们每个人增加一个等级 - 一个是赔率,一个是平均值。
select @rank := @rank + 2 `rank`, *
from table1, (select @rank := -1) q
where column1 = 'anything'
union all
select @rank2 := @rank2 + 2 `rank`, *
from table2, (select @rank2 := 0) q
where column1 = 'anything'
order by rank asc;
sqlfiddle看起来已经失败了我会创建一个演示,但它应该可以工作。
@rank
和@rank2
是变量。对于结果集中的每一行,@rank2 := @rank2 + 2
为@rank
增加2
,并在结果中包含新值。
from table2, (select @rank2 := 0) q
只是一种强制变量初始化为0
而无需运行其他查询的方法。通过在-1
处为第一个查询启动排名计数器,为第二个查询启动-0
,第一个查询中的每一行都会在序列1,3,5,7,...
中获得一个排名,并且第二个查询接收序列2,4,6,8,...
示例
mysql> create table table1 (id integer primary key auto_increment, column1 varchar(25));
Query OK, 0 rows affected (0.08 sec)
mysql> create table table2 (id integer primary key auto_increment, column1 varchar(25));
Query OK, 0 rows affected (0.08 sec)
mysql> insert into table1 (column1) values ('abcd'), ('lmno'), ('abcd'), ('lmno'), ('pqr');
Query OK, 5 rows affected (0.03 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> insert into table2 (column1) values ('lmno'), ('abcd'), ('abcd'), ('lmno'), ('abcd'), ('abcd'), ('abcd');
Query OK, 7 rows affected (0.05 sec)
Records: 7 Duplicates: 0 Warnings: 0
和数据:
mysql> select * from table1;
+----+---------+
| id | column1 |
+----+---------+
| 1 | abcd |
| 2 | lmno |
| 3 | abcd |
| 4 | lmno |
| 5 | pqr |
+----+---------+
5 rows in set (0.00 sec)
mysql> select * from table2;
+----+---------+
| id | column1 |
+----+---------+
| 1 | lmno |
| 2 | abcd |
| 3 | abcd |
| 4 | lmno |
| 5 | abcd |
| 6 | abcd |
| 7 | abcd |
+----+---------+
7 rows in set (0.00 sec)
结果:
mysql> select @rank := @rank + 2 `rank`, id from table1, (select @rank := -1) q where column1 = 'abcd' union select @rank2 := @rank2 + 2 `rank`, id from table2, (select @rank2 := 0) q where column1 = 'abcd' order by rank asc;
+------+----+
| rank | id |
+------+----+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 3 |
| 6 | 5 |
| 8 | 6 |
| 10 | 7 |
+------+----+
7 rows in set (0.00 sec)