union命令选择错误

时间:2013-09-08 15:46:57

标签: sql select union

我有一张名为mytable的表格,含有这些结果

ID | name
----------
1  | one
2  | two
3  | three
4  | four
5  | five


我需要这个结果

ID | name
----------
3  | three
1  | one
2  | two
4  | four
5  | five

记录'3,三'必须在第一行,然后其他人将在此记录后显示。谢谢你;

4 个答案:

答案 0 :(得分:1)

试试这个:

select ID, NAME from 
    (select *, -1 as rnum from tb where id=3
    union all
    select *, ID as rnum from tb where id!=3 ) tb1
ORDER BY rnum ASC

这是SQLfiddle

答案 1 :(得分:0)

select * from mytable s where s.id=3
union all
select * from ( 
    select t.id,t.name from mytable t where t.id!=3
order by t.id) as q;

SQLfiddle demo

答案 2 :(得分:0)

试试这个。它应该在PostgreSQL,MySQL和SQLServer中运行

SELECT ID, Name
FROM (
  SELECT 1 AS ID,  'one' as NAME 
  UNION SELECT 2 , 'two'
  UNION SELECT 3 , 'three'
  UNION SELECT 4 , 'four'
  UNION SELECT 5 , 'five'

) AS MyDataSet
ORDER BY CASE WHEN ID = 3 THEN 0 ELSE 1 END

答案 3 :(得分:0)

使用标准SQL,您可以简单地根据您想要的行排序(返回该特定行的值低于所有其他行的值),然后是ID。

SELECT * FROM mytable
ORDER BY CASE WHEN name='three' THEN 0 ELSE 1 END, ID

An SQLfiddle to test with

相关问题