【YashanDB知识库】MySQL field 函数的改写方法

本文内容来自YashanDB官网,原文内容请见https://www.yashandb.com/newsinfo/7664893.html?templateId=1718516

概述
MySQL field函数常用于自定义排序,改写到YashanDB一般用decode或者case进行改写。

详情
MySQL的field用法
MySQL的field函数一般用于对SQL中查询结果集进行指定顺序排序,例如以下查询对于c2列,如果c2的值等于'plane','train','bicycle'其中之一,则以 'plane','train','bicycle'的顺序编号1,2,3进行排序,否则顺序编号为0,排在最前。请看以下示例:

mysql> select c1, c2 from t1 order by field (c2, 'plane','train','bicycle');

+----+---------+

| c1 | c2 |

+----+---------+

| 1 | car |

| 5 | rocket |

| 2 | plane |

| 4 | train |

| 3 | bicycle |

+----+---------+

5 rows in set (0.00 sec)

表和数据

create table t1(c1 int primary key, c2 varchar(100));

insert into t1 values(1,'car'),(2,'plane'),(3,'bicycle'),(4,'train'),(5,'rocket');

commit;

YashanDB的改写方法
可以用decode或者case进行改写

SQL> select c1, c2 from t1 order by decode (c2, 'plane', 1, 'train', 2, 'bicycle', 3, 0);

 

         C1 C2

----------- ----------------------------------------------------------------

          1 car

          5 rocket

          2 plane

          4 train

          3 bicycle

 

5 rows fetched.

 

SQL> select c1, c2 from t1 order by case c2 when 'plane' then 1 when 'train' then 2 when 'bicycle' then 3 else 0 end;

 

         C1 C2

----------- ----------------------------------------------------------------

          1 car

          5 rocket

          2 plane

          4 train

          3 bicycle

 

5 rows fetched.
posted @   YashanDB  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· 【全网最全教程】使用最强DeepSeekR1+联网的火山引擎,没有生成长度限制,DeepSeek本体
点击右上角即可分享
微信分享提示