mysql - Select MAX in mixed int/string in SQL database
问题描述
I have the following database:
+-------------+
| rd |
+-------------+
| 65000807:11 |
| 65000807:9 |
| 65000809:10 |
+-------------+
I would like to select the biggest value, which is 65000807:11
(the biggest number after the :
). With the following query, I can get 11
, but I need to get the whole string. How could I do that?
SELECT MAX(CAST(SUBSTRING(rd,10,length(rd)-9) AS UNSIGNED)) AS 'rd' from myTable;
解决方案
You can use your substring in an order by clause and get 1 result :
Schema (MySQL v8.0)
CREATE TABLE myTable (
`rd` VARCHAR(11)
);
INSERT INTO myTable
(`rd`)
VALUES
('65000807:11'),
('65000807:9'),
('65000809:10');
Query #1
SELECT rd
FROM myTable
ORDER BY CAST(SUBSTRING(rd,10,length(rd)-9) AS UNSIGNED) DESC
LIMIT 1;
Output :
| rd |
| ----------- |
| 65000807:11 |
However, I would advice you to re-think the design of the table, you are storing 2 informations in the same column, which goes against the purpose of using a RDBMS
推荐阅读
- react-native - 在物理设备上运行 React Native@0.66.1 和 react-devtools@4.21.0 的问题
- python - 无法将图像加载到 QGraphicsView(浮点除以零)。识别矩形,但不会设置场景
- python - 根据另一个字典的值修改字典,以查找两个字典中的相同键
- python - 将数据框列值拆分为大小为 n 的窗口并保留日期信息
- python - 如何将浮动分组到垃圾箱中?
- css - 进行 API 调用时如何将 css 动画添加到 vue.js
- android - 如何使用单独的按钮制作颜色选择器?
- json - 无法使用嵌入对象发布 JSON - 它读取并存储除对象列表 (OneToMany) 之外的所有内容 - Spring Boot API (+ hibernate)
- reactjs - WordPress 作为带有 Next.js 的无头 CMS - 使用代码突出显示片段呈现帖子内容的问题
- c++ - 如何为 clang 的 C++20 功能正确设置 ccls?