gpt4 book ai didi

mysql - 从字符串 MySQL 中选择前 4 个数字

转载 作者:行者123 更新时间:2023-11-29 05:06:44 24 4
gpt4 key购买 nike

如果我有这样的字符串:

CC123484556
CC492014512
BUXT122256690

我如何在 MySQL 中操作这样的代码来提取前 4 个数字值?在其他行的数字之前有各种 # 字母,但最重要的是显示的前 4 个数字。

SELECT LEFT(alloy , 4) FROM tbl 

所以期望的结果是:

1234
4920
1222

最佳答案

缓慢而丑陋:

SELECT col,
SUBSTRING(tab.col, MIN(LOCATE(four_digits, tab.col,1)), 4) + 0 AS result
FROM (SELECT 'CC123484556' AS col UNION ALL
SELECT 'CC492014512' UNION ALL
SELECT 'BUXT122256690' UNION ALL
SELECT 'abced') tab
CROSS JOIN (
SELECT CONCAT(d1.z, d2.z, d3.z, d4.z) AS four_digits
FROM (SELECT '1' AS z UNION SELECT '2' UNION SELECT '3' UNION
SELECT '4' UNION SELECT '5' UNION SELECT '6' UNION
SELECT '7' UNION SELECT '8' UNION SELECT '9' UNION SELECT '0') d1
CROSS JOIN (SELECT '1' AS z UNION SELECT '2' UNION SELECT '3' UNION
SELECT '4' UNION SELECT '5' UNION SELECT '6' UNION
SELECT '7' UNION SELECT '8' UNION SELECT '9' UNION SELECT '0') d2
CROSS JOIN (SELECT '1' AS z UNION SELECT '2' UNION SELECT '3' UNION
SELECT '4' UNION SELECT '5' UNION SELECT '6' UNION
SELECT '7' UNION SELECT '8' UNION SELECT '9' UNION SELECT '0') d3
CROSS JOIN (SELECT '1' AS z UNION SELECT '2' UNION SELECT '3' UNION
SELECT '4' UNION SELECT '5' UNION SELECT '6' UNION
SELECT '7' UNION SELECT '8' UNION SELECT '9' UNION SELECT '0') d4
) sub
WHERE LOCATE(four_digits, tab.col,1) > 0
GROUP BY col;

Rextester Demo

生成所有 4 位数字组合,在字符串中定位它们并获取索引最低的子字符串。

编辑:

更快一点的方法:

SELECT col, SUBSTRING(col, MIN(i), 4) + 0 AS r
FROM (
SELECT col, SUBSTRING(tab.col, i , 4) + 0 AS result, i
FROM tab
CROSS JOIN (
SELECT CONCAT(d1.z, d2.z)+1 AS i
FROM (SELECT '1' AS z UNION SELECT '2' UNION SELECT '3' UNION
SELECT '4' UNION SELECT '5' UNION SELECT '6' UNION
SELECT '7' UNION SELECT '8' UNION SELECT '9' UNION SELECT '0') d1
CROSS JOIN (SELECT '1' AS z UNION SELECT '2' UNION SELECT '3' UNION
SELECT '4' UNION SELECT '5' UNION SELECT '6' UNION
SELECT '7' UNION SELECT '8' UNION SELECT '9' UNION SELECT '0') d2
) sub
WHERE i <= LENGTH(tab.col)-1
) sub
WHERE result <> 0
GROUP BY col;

Rextester Demo2

从头开始获取4个字符的子串,隐式转换为数字,得到i最小的数字。

关于mysql - 从字符串 MySQL 中选择前 4 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46471313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com