从单个表中进行双重排序选择

时间:2010-08-05 15:04:22

标签: sql mysql

我有一个表,其中id为主键,而描述为另一个字段。

我想首先选择id <= 4的记录,按描述排序,然后我想要所有其他记录(id> 4),按描述排序。无法到达那里!

5 个答案:

答案 0 :(得分:4)

select id, descr
from t
order by 
 case when id <= 4 then 0 else 1 end, 
 descr

答案 1 :(得分:2)

select *, id<=4 as low from table order by low, description

答案 2 :(得分:1)

您可能希望在id <= 4子句中使用ORDER BY表达式:

SELECT * FROM your_table ORDER BY id <= 4 DESC, description;

测试用例(使用MySQL):

CREATE TABLE your_table (id int, description varchar(50));

INSERT INTO your_table VALUES (1, 'c');
INSERT INTO your_table VALUES (2, 'a');
INSERT INTO your_table VALUES (3, 'z');
INSERT INTO your_table VALUES (4, 'b');
INSERT INTO your_table VALUES (5, 'g');
INSERT INTO your_table VALUES (6, 'o');
INSERT INTO your_table VALUES (7, 'c');
INSERT INTO your_table VALUES (8, 'p');

结果:

+------+-------------+
| id   | description |
+------+-------------+
|    2 | a           |
|    4 | b           |
|    1 | c           |
|    3 | z           |
|    7 | c           |
|    5 | g           |
|    6 | o           |
|    8 | p           |
+------+-------------+
8 rows in set (0.00 sec)

相关文章:

答案 3 :(得分:1)

select id, description
from MyTable
order by case when id <= 4 then 0 else 1 end, description

答案 4 :(得分:1)

您可以使用UNION

SELECT * FROM (SELECT * FROM table1 WHERE id <=4 ORDER by description)aaa
UNION
SELECT * FROM (SELECT * FROM table1 WHERE id >4 ORDER by description)bbb

OR

SELECT * FROM table1
ORDER BY
CASE WHEN id <=4 THEN 0
ELSE 1
END, description