当前位置:网站首页>MySQL-字符串按照数值排序
MySQL-字符串按照数值排序
2022-07-23 11:42:00 【JustDI-CM】
1.需求
MySQL 有个表字段设计的时候,设置为了 varchar 类型,存取的却是数值,后续有业务需要按照此字段排序,获取最大值。
按照最原始的排序语句为:
SELECT * FROM test_21 a ORDER BY a.testId desc;
结果为:
这个并不是想要的结果。
2.方法
改造一下
1)与 int 进行计算
SELECT * FROM test_21 a ORDER BY a.testId+0 desc;
SELECT * FROM test_21 a ORDER BY a.testId-2 desc;
SELECT * FROM test_21 a ORDER BY a.testId*1 desc;
SELECT * FROM test_21 a ORDER BY a.testId/4 desc;
MySQL 的 varchar 与 int 计算时,会转换为 int。
以上4个 sql 的执行结果都为
2)cast() 或 convert()
SELECT * FROM test_21 a ORDER BY cast(a.testId as SIGNED) desc;
SELECT * FROM test_21 a ORDER BY convert(a.testId,SIGNED) desc;
这两个函数都是用于格式转换的,二者没什么区别,
语法为:
CAST(expr AS type)
CONVERT(expr,type)
支持的类型有
| 值 | 说明 |
|---|---|
| DATE | 将expr转换成’YYYY-MM-DD’格式 |
| DATETIME | 将expr转换成’YYYY-MM-DD HH:MM:SS’格式 |
| TIME | 将expr转换成’HH:MM:SS’格式 |
| CHAR | 将expr转换成CHAR(固定长度的字符串)格式 |
| SIGNED | 将expr转换成INT(有符号的整数)格式 |
| UNSIGNED | 将expr转换成INT(无符号的整数)格式 |
| DECIMAL | 将expr转换成FLOAT(浮点数)格式 |
| BINARY | 将expr转换成二进制格式 |
结果都为:
边栏推荐
- 上课作业(5)——#576. 饥饿的牛(hunger)
- Opnsense - multifunctional, highly reliable and easy-to-use firewall (II)
- SSB signal modulation and demodulation based on MATLAB (with source code)
- [attack and defense world web] difficulty Samsung 9 points introductory question (Part 1): simple_ js、mfw
- 记一次SQL优化
- [attack and defense world web] difficulty Samsung 9 points introductory question (Part 2): shrink, lottery
- MD5 strong collision, secondary decoding,
- Vim到底可以配置得多漂亮?
- As a tester, you cannot fail to understand ADB commands and operations
- The difference between cookies and sessions
猜你喜欢

来自大佬洗礼!2022头条首发纯手打MySQL高级进阶笔记,吃透P7有望

云服务器ECS远程监控

Day14 function module

After Effects 教程,如何在 After Effects 中创建动画?

Bug modification

Without Huawei, Qualcomm will raise prices at will, and domestic mobile phones that lack core technology can only be slaughtered

Unity notes ilruntime access

奔驰新能源产品线:豪华新能源市场或将改变格局

【攻防世界WEB】难度三星9分入门题(中):ics-05、easytornado

【运维】ssh tunneling 依靠ssh的22端口实现访问远程服务器的接口服务
随机推荐
Kirin V10 source code compilation qtcreater4.0.3 record
Quickly master QML Chapter 5 components
redis 主从复制
C语言书籍推荐
重磅 | CertiK:2022年第二季度Web3.0行业安全报告发布(附PDF下载链接)
忘记oracle密码,如何解决
《快速掌握QML》第四章 事件处理
[7.16] code source - [array division] [disassembly] [select 2] [maximum common divisor]
关于初始化page入参的设计思路
(Zset) how is the underlying layer of redis stored with a hop table
备份内容哈哈哈
aws篇4 一机一密
云服务器ECS远程监控
【攻防世界WEB】难度三星9分入门题(上):simple_js、mfw
SCA在得物DevSecOps平台上应用
专访|开源之夏新星牛学蔚
Design idea of initializing page input parameters
3D math - vector
xml-xxe漏洞之Fake XML cookbook
printf函数-转换说明