我的sql查询独立查找排序两列

时间:2015-04-07 06:12:13

标签: mysql sql

有一个表有两列,比如id和name,我想要对两列进行排序。

table :
id name
3 y
2 z
1 x

output should be
id name
1 x
2 y
3 z

任何人都可以在单个SQL查询中执行吗???

2 个答案:

答案 0 :(得分:1)

你需要做一些奇怪的事情。因为你想要做的事情很奇怪。

select b1.id, b2.name from
(
  select @row := @row +1 as row, id
    from broken, (select @row := 0) rr
  order by id asc
) b1
inner join
(
  select @row2 := @row2 + 1 as row, name
    from broken, (select @row2 := 0) rr
  order by name asc
) b2
on b1.row = b2.row

演示小提琴:http://sqlfiddle.com/#!9/4d47c/7

答案 1 :(得分:0)

Select *
, row_number() over (order by ID) as IDRow
, row_number() over (order by name) as NameRow
into #temp
from table

select a.ID, b.Name from #temp a
full outer join #temp b
on a.IDRow = b.NameRow
order by IDRow, NameRow

如果您愿意,可以使用子查询而不是临时表来执行此操作,但这种方式可能会更快。