2015-10-16 82 views
1

我有一个查询由三个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不为我工作)

+0

你有3个表责令结果和您选择3列对于每个表,并让它们显示在一列上,实际上每个表需要3个联合。你能否提供一些样本数据以及表格?另外,当你选择没有命令,然后不能保证它们将以什么顺序显示,就像你对第一个查询结果显示为'红色,绿色,蓝色,黄色' –

+0

@AbhikChakraborty我的问题已更新。 – Shafizadeh

回答

1

这是你如何能做到这

select @rn:[email protected]+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,.... table21.5,2.5,3.5,.... table31.6,2.6,....

所以最后当你所有的氡将它作为

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

+0

你的大脑是值得赞美的!每次我看到我喜欢的答案。干得好的朋友! +1 – Shafizadeh

+0

只是一个问题:何时这有用? '@rn:= @ rn + 1作为id',以及为什么'作为id'?因为那里有一个名为'id'的真正列, – Shafizadeh

+1

原因是上面的查询是从已经选择的数据中选择数据。现在,如果您注意到我们只选择了'color'和'rn'这是我们为每个查询计算的行数,而外部select查询只是根据所有选定行计算某个增量数的另一种方法。如果我们碰巧在内部查询中选择了ids,那么你可能会得到像'1,1,2,2,....'等不太好看的id的结果。 –

相关问题