ITPub博客

首页 > 数据库 > 国内数据库 > 【YashanDB 知识库】MySQL field 函数的改写方法

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

原创 国内数据库 作者:崖山数据库系统YashanDB 时间:2025-02-11 15:29:36 0 删除 编辑

本文内容来自 YashanDB 官网,原文内容请见  https:///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.


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70028812/viewspace-3071699/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
崖山数据库系统YashanDB是深圳计算科学研究院完全自主研发设计的新型数据库系统,融入原创理论,支持单机/主备、共享集群、分布式等多种部署方式,覆盖OLTP/HTAP/OLAP交易和分析混合负载场景,为客户提供一站式的企业级融合数据管理解决方案。

注册时间:2023-04-11

  • 博文量
    722
  • 访问量
    640394