zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

sql server自定义排序(还有mysql)

mysqlserverSQL排序 自定义 还有
2023-09-11 14:21:09 时间

【1】sql server自定义排序

 

1. c2列的数据按'4','1','2'的指定顺序排序

(1) 使用union

复制代码
select * from t_orderby 
where c2='4' 
union all 
select * from t_orderby 
where c2='1' 
union all 
select * from t_orderby 
where c2='2'
复制代码

 (2) charindex

select * from t_orderby 
order by charindex(c2,'4,1,2') 

 (3) case when

复制代码
select * from t_orderby 
order by case 
         when c2='4' then 1 
         when c2='1' then 2 
         when c2='2' then 3 
         end,c1 desc
复制代码

 

2. 随机排序

(1) 要求c2='4'排第一行,其他的行随机排序

select * from t_orderby 
order by case 
         when c2='4' then 1 
         else 1+rand() 
         end

 (2) 所有行随机排序

select * from t_orderby 
order by newid()

 (3) 随机取出第一行

select top 1 * from t_orderby 
order by newid()

 

3. 要求列c3中数据,先按第一个字符排序,再按第二个字符排序

select * from t_orderby 
order by left(c3,1),ASCII(substring(c3,2,1))

 

【2】mysql自定义排序

 

问题描述
 

大家都知道, MySQL 中按某字段升序排列的 SQL 为 (以 id 为例, 下同):

SELECT * FROM `MyTable` 
WHERE `id` IN (1, 7, 3, 5) 
ORDER BY `id` ASC
降序排列的 SQL 为:

SELECT * FROM `MyTable` 
WHERE `id` IN (1, 7, 3, 5) 
ORDER BY `id` DESC
有时以上排序并不能满足我们的需求. 例如, 我们想要按 id 以 5, 3, 7, 1 的顺序排列, 该如何实现. 这也是很多国内外同行经常遇到的问题之一.

下面我们给出按表中某字段, 以我们想要的列表方式排序的解决方案.

解决方案
  用"按字段排序" (ORDER BY FIELD).

语法
ORDER BY FIELD(`id`, 5, 3, 7, 1)
要注意的是, FIELD 后面是没有空格的.

因此, 完整的 SQL 为:

SELECT * FROM `MyTable` 
WHERE `id` IN (1, 7, 3, 5) 
ORDER BY FIELD(`id`, 5, 3, 7, 1)
常见应用
SELECT * FROM `MyTable` 
WHERE `name` IN ('张三', '李四', '王五', '孙六') 
ORDER BY FIELD(`name`, '李四', '孙六', '张三', '王五')

参考资料

Handy MySQL - ORDER BY FIELD

Sort results by order in list